'Merge arrays from object property in an object array [closed]
Give an array of objects as below:
var objArray = [{'key': 'key1', 'fields': [1, 2]}, {'key': 'key2', 'fields': [3, 4]}];
I would like to get an array of merged items from fields property and output should be 1, 2, 3, 4
I've tried to merge as below. I'm not satisfied with my solution and would like to get feedback's and improve upon my solution. I'm new to JS and typescript. I believe there is better solution with features of ES6. Can someone help to improve my solution?
function mergeArraysFromObjectArray(objArray){
let allFields = [];
for (let obj of objArray) {
for (let propt in obj) {
if (obj.hasOwnProperty(propt) && propt === 'fields') {
allFields = allFields.concat(obj[propt]);
}
}
}
return allFields;
}
var objArray = [{'key': 'key1', 'fields': [1, 2]}, {'key': 'key2', 'fields': [3, 4]}];
let allMergedFields = mergeArraysFromObjectArray(objArray);
for(let i=0; i < allMergedFields.length; i++){
console.log(allMergedFields[i]); //prints - 1, 2, 3, 4
}
Solution 1:[1]
You can use Array.prototype.flatMap()
Code example 1:
const objArray = [{key: 'key1', fields: [1, 2]}, {key: 'key2', fields: [3, 4]}]
const result = objArray.flatMap(({ fields }) => fields)
console.log(result)
Also you can use Array.prototype.map() and Array.prototype.flat()
Code example 2:
const objArray = [{key: 'key1', fields: [1, 2]}, {key: 'key2', fields: [3, 4]}]
const result = objArray.map(({ fields }) => fields).flat()
console.log(result)
Also you can use Array.prototye.reduce() combined with destructuring assignment and spread syntax
Code example 3:
const objArray = [{key: 'key1', fields: [1, 2]}, {key: 'key2', fields: [3, 4]}]
const result = objArray.reduce((a, { fields }) => [...a, ...fields], [])
console.log(result)
Also using just Array.prototye.reduce() combined with Array.prototype.map():
Code example 4:
const objArray = [{key: 'key1', fields: [1, 2]}, {key: 'key2', fields: [3, 4]}]
const result = objArray.reduce((a, { fields }) => a.concat(fields), [])
console.log(result)
Solution 2:[2]
You can use spread syntax ... and map() to get fields property
var objArray = [{'key': 'key1', 'fields': [1, 2]}, {'key': 'key2', 'fields': [3, 4]}];
var result = [].concat(...objArray.map(({fields}) => fields))
console.log(result)
You can also add filter(Boolean) to remove undefined in case there is no fields property.
var objArray = [{'key': 'key1', 'asdf': [1, 2]}, {'key': 'key2', 'fields': [3, 4]}];
var result = [].concat(...objArray.map(e => e.fields).filter(Boolean))
console.log(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
