0

I have this array:

let mainArray = [
  {
    "key1": "value1"     //           <------------
  },                     //                       |
  {                      //                       |
    "key2": "value2"     //                       |  key1 exists two times
  },                     //                       | 
  {                      //                       |
    "key1": "toAddValue" //           <------------
  }
]; 

Expected Output:

Key1 value should be in a Single array

[
    {
        'item': {
            'data': ['value1', 'toAddValue'], //  <-- It's values should be in Single arr
            'path': 'key1'    //                  <-- It's key name in path field.
        }
    },
    {
        'item': {
            'data': ['value2'],               // <-- its' value occurs once
            'path': 'key2'                    // <-- so it should be in one array.
        }
    }
]

Question:

If any of the key of mainArray is re-occurring / Repeating then, it should be added into single array called data

How do I do this?

var secondArray = []; // New array where all outputs are collected
let mainArray = [{
    "key1": "value1"
  },
  {
    "key2": "value2"
  },
  {
    "key1": "newKeyVal"
  }
];


for (let i = 0; i <= mainArray.length; i++) {
  for (let j = 0; j <= secondArray.length; j++) {

    if (secondArray.length == 0) {
      secondArray.push({
        "item": {
          'data': [Object.values(i)[0]],
          'path': `${Object.keys(i)[0]}`
        }
      })
    }
    if (secondArray[j].item.path === Object.keys(i)[0]) {
      secondArray[j].item.data.push([Object.values(i)[0]])
    }
  }
}
console.log(secondaryArray)
mplungjan
  • 155,085
  • 27
  • 166
  • 222

0 Answers0