-1

I am trying to add existing key value to the new key wrt to the same key, I might not be able to explain it clearly with my words, but below data can make sense.

I have my data in below formate

const sampelData = [{
    'car1 critical':  [1, 1, 1, 1, 1, 1],
    'car1 good':  [1, 1, 1, 1, 1, 1, 1],
    'car1 warning':  [1, 1, 1, 1, 1, 1],
    'car2 critical':  [0, 0, 0, 0, 0,0],
    'car2 good':  [0, 0, 0, 0, 0, 0],
    'car2 warning': [0, 0, 0, 0, 0, 0]
 }]

and i want to manipulate in such a way that array will get assign to new key with in the same key with some more object

 Desired output :-
    [{
            'car1 critical':  {data:[1, 1, 1, 1, 1, 1], condition:"critical"},
            'car1 good':  {data:[1, 1, 1, 1, 1, 1], condition:"good"},
            'car1 warning':  {data:[1, 1, 1, 1, 1, 1], condition:"warning"},
            'car2 critical':  {data:[0, 0, 0, 0, 0, 0], condition:"critical"},
            'car2 good':  {data:[0, 0, 0, 0, 0, 0], condition:"good"},
            'car2 warning': {data:[0, 0, 0, 0, 0, 0], condition:"warning"}
   }]

If there are any other ways of handling such data, any info related to this will be very knowledgeable and helpful.

Yasin Br
  • 1,675
  • 1
  • 6
  • 16
Rock Havmor
  • 81
  • 1
  • 9
  • If you share what you have tried or what you think about the solution it will lead to better responses. – Tushar Shahi Feb 15 '22 at 19:09
  • Does this answer your question? [map function for objects (instead of arrays)](https://stackoverflow.com/questions/14810506/map-function-for-objects-instead-of-arrays) – Serlite Feb 15 '22 at 19:17

1 Answers1

1

You can use Array map() with a for..in loop to itirate thru each object and modify its value. Here is an example:

const sampleData = [{
  'car1 critical': [1, 1, 1, 1, 1, 1],
  'car1 good': [1, 1, 1, 1, 1, 1, 1],
  'car1 warning': [1, 1, 1, 1, 1, 1],
  'car2 critical': [0, 0, 0, 0, 0, 0],
  'car2 good': [0, 0, 0, 0, 0, 0],
  'car2 warning': [0, 0, 0, 0, 0, 0]
}]

// map sampleData
sampleData.map(item => {
  // Iterate object in sampleData
  for (let i in item) {
    // assign new value to each item in object
    item[i] = {
      data: item[i],
      condition: i.split(' ')[1]
    }
  }
})

console.log(sampleData)
Timur
  • 1,682
  • 1
  • 4
  • 11