1

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

2
  • Shortcut for your if..else block: result.score = result.score || '' Commented Sep 6, 2018 at 9:16
  • Try Object.keys(result).forEach((key) => result[key].forEach((obj) => obj.score = obj.score || ''; )) Commented Sep 6, 2018 at 9:18

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.