简体   繁体   中英

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)

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM