-2

I am trying to push multiple values in array like

arr.push({y: val.date})
for(var n = 0; n < 4; n++) {
    arr.push({'"+val+n+"': data["+n+"]});
}

Result is like:

[
  {
    "y": "2019-09-08 16:41:04"
  },
  {
    "D0": "31.70"
  },
  {
    "D1": "31.70"
  },
  {
    "D2": "31.70"
  },
  {
    "D3": "31.80"
  }
]

But i want array to look like this:

{
  "y": "2019-09-08 16:41:04",
  "D0": "31.70",
  "D2": "31.70",
  "D3": "31.70",
  "D4": "31.80"
}

I tried to merge and concatenate but its not working. Is there any way because my key & values are generated dynamically with json data.

Below code comes from other source that is why i had to do it like that

arr.push({y: val.date})
3
  • 1
    Right, so, if you want an object, you'll need to use an object instead of an array. Commented Sep 16, 2019 at 19:15
  • Possible duplicate of stackoverflow.com/questions/1334660/… Commented Sep 16, 2019 at 19:17
  • Read up on the difference between an object and an array. You're mixing the 2 concepts together Commented Sep 16, 2019 at 19:18

2 Answers 2

0

Thanks but i found my answer, right after posting this question. Thanks

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});
Sign up to request clarification or add additional context in comments.

Comments

-1

Does this solve your problem:

// ES2018
let obj = {}
for (let i = 0; i < 10; i++) {
  obj = { ...obj, ...{[`val${i}`]: i} }
}

//ES5
var obj = {}
for (var i = 0; i < 10; i++) {
  obj = Object.assign( obj, { [`val${i}`]: i })
}

1 Comment

O okay, I see a down vote. Doesn't my answer helped at all? Perhaps I can rephrase or elaborate a bit. My answers goes more into detail about merging object. Nevertheless I am glad to see you figured it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.