Jeery sum code
Jeery sum code

Reputation: 118

Merging multiple arrays inside an objects into a single array

My Object contains different datatypes including array. I want to concatenate all arrays(in a single array) I have written using foreach and concat.

Is there any way I can have a better solution, or this is correct?

See the below snippet. concat array value3 and value5 into single array.

var Input = {
    "value1": 10,
    "value2": "abcd",
    "value3": [
        {
            "v1": 100,
            "v2": 89
        },
        {
            "v1": 454,
            "v2": 100
        }
    ],
    "value4": "xyz",
    "value5": [
        {
            "v6": 1,
            "v7": -8
        },
        {
            "v1": 890,
            "v2": 10
        }
    ]
}

   
var OutputData = [];
  let keys = Object.keys(Input);
  keys.forEach(key => {
    if (Array.isArray(Input[key])) {
      try {
        OutputData= OutputData.concat(Input[key])
      } catch (error) {
      }
    }
  });
  
console.log(OutputData)

Upvotes: 2

Views: 1374

Answers (2)

phi-rakib
phi-rakib

Reputation: 3302

You could use Array.prototype.filter() with Array.prototype.flat() method get a cleaner code. First get all the values using Object.values() method. Then use filter method to get the arrays and at last use flat method to get a new array with all sub-array elements concatenated.

const input = {
  value1: 10,
  value2: 'abcd',
  value3: [
    {
      v1: 100,
      v2: 89,
    },
    {
      v1: 454,
      v2: 100,
    },
  ],
  value4: 'xyz',
  value5: [
    {
      v6: 1,
      v7: -8,
    },
    {
      v1: 890,
      v2: 10,
    },
  ],
};

const ret = Object.values(input)
  .filter((x) => Array.isArray(x))
  .flat();
console.log(ret);

Upvotes: 3

hamid niakan
hamid niakan

Reputation: 2851

I think this might be a little bit cleaner to read:

var input = {
  "value1": 10,
  "value2": "abcd",
  "value3": [{
      "v1": 100,
      "v2": 89
    },
    {
      "v1": 454,
      "v2": 100
    }
  ],
  "value4": "xyz",
  "value5": [{
      "v6": 1,
      "v7": -8
    },
    {
      "v1": 890,
      "v2": 10
    }
  ]
};

let res = [];

for (let k in input) {
  if (input.hasOwnProperty(k) && Array.isArray(input[k]))
    input[k].forEach(x => res.push(x));
}

console.log(res);

Upvotes: 1

Related Questions