Search code examples
javascriptarraysobjectlodash

Check and add for property in object of arrays


I have an object/output in a very specific format detail below:

result = 
AB: [ 0:{Name: "Tom", team:"Spirit", position: "Defender", score: 22 }
    1:{Name: "Paul", team:"Vikings", position: "center" }
    2:{Name: "Jim", team:"United", position: "Wing", }
    3:{Name: "Greg", team:"Crusaders", position: "Fullback", score: 54}
    4:{Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }
    ]
CD: [0:{...},1:{...},2:{...},3:{...},4:{...}]
EF: [0:{...},1:{...},2:{...},3:{...},4:{...}]
GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]

The result has nested arrays. On some outputs the property of score is not there, but I need it to be - if its not there I need to add it by default as score:"" if it is there then just leave it alone.

I have been able to add the property of score but only at the top level of the result object e.g.

...
    GH: [0:{...},1:{...},2:{...},3:{...},4:{...}]
    score:""

by

 if(result.hasOwnProperty("score")) {
     alert('Item has already that property');
 } else {
     result.score = "" ;
 }

I can target a specific path by(below) but I want to apply it to all:

 if(finalResult['AB'][1].hasOwnProperty("durabilityScore")) {
    alert('Item has already that property');
} else {
    finalResult['AB'][1].durabilityScore = 'value';
}

I am using Lodash if that helps. Thanks


Solution

  • You could iterate the values of the object and the array. Then check if the property exists and assign a value if not.

    This solution does not overwrite falsy values (0, '', false, undefined, null), which would happen if used a default check, like

    o.score = o.score || ''
    

    var result = { AB: [{ Name: "Tom", team:"Spirit", position: "Defender", score: 22 }, { Name: "Paul", team:"Vikings", position: "center" }, { Name: "Jim", team:"United", position: "Wing" }, { Name: "Greg", team:"Crusaders", position: "Fullback", score: 54 }, { Name: "Tim", team:"Vikings", position: "Fullback", score: 77 }] };
    
    Object.values(result).forEach(a => a.forEach(o => 'score' in o || (o.score = '')));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }