-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})
DIGITAL JEDI
  • 1,672
  • 3
  • 24
  • 52

2 Answers2

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});
DIGITAL JEDI
  • 1,672
  • 3
  • 24
  • 52
-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 })
}
  • 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 :) – Rick van den Broek Sep 16 '19 at 19:43