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
}
Advertisement
Answer
You can simply concat the array and create a new array inside a loop:
var objArray = [{'key': 'key1', 'fields': [1, 2]}, {'key': 'key2', 'fields': [3, 4]}];
var result = [];
for(var i=0; i<objArray.length; i++){
result = result.concat(objArray[i].fields);
}
console.log(result);