I m working on nested array of objects, where I require return to be a specific string from an object which satisfies below conditions as shown in the code. But as we know forEach returns undefined, and my requirement is a single string as return, can any new es6 in built array functions be used to make it more easy? in below code value in second loop is received from a function, so ignore its source
const data = [
{
column:"a" ,
children:[
{column: "a1", area: { defaultValue:"NY", selectedValue: "NJ"} },
{column: "a2", area: { defaultValue:"IN", selectedValue: "CA"} },
]
},
{
column:"b" ,
children:[
{column: "b1", area: { defaultValue:"JP", selectedValue: "CC"} },
{column: "b2", area: { defaultValue:"CA", selectedValue: "BL"} },
]
},
];
const newValue = data.forEach( d => {
if (d.column === "a" && children) {
children.forEach(c => {
if (c.column === value) {
return c.area.selectedValue || c.area.defaultValue;
}
})
}
})
console.log(newValue);
CodePudding user response:
This may be one possible way to obtain the desired objective:
const getNewValue = (val1 = 'a', val2 = 'a2') => {
const foundIt = data?.find(
d => d.column === val1
)?.children?.find(
c => c.column === val2
);
return foundIt?.area?.selectedValue ||
foundIt?.area?.defaultValue ||
'No matching entry found';
}
Explanation
- Use
findto get a match on thecolumn. - Use
?.optional-chaining to referchildrenwithin the matched object .findthe matching value (such asa1, ora2, etc) within children- return either the
selectedValueordefaultValueor, if both are falsy, a string-constant to notify no matches.
Code Snippet
const data = [
{
column:"a" ,
children:[
{column: "a1", area: { defaultValue:"NY", selectedValue: "NJ"} },
{column: "a2", area: { defaultValue:"IN", selectedValue: "CA"} },
]
},
{
column:"b" ,
children:[
{column: "b1", area: { defaultValue:"JP", selectedValue: "CC"} },
{column: "b2", area: { defaultValue:"CA", selectedValue: "BL"} },
]
},
];
const getNewValue = (val1 = 'a', val2 = 'a2') => {
const foundIt = data?.find(
d => d.column === val1
)?.children?.find(
c => c.column === val2
);
return foundIt?.area?.selectedValue ||
foundIt?.area?.defaultValue ||
'No matching entry found';
}
console.log(getNewValue());
console.log(getNewValue('a', 'a1'));
console.log(getNewValue('b', 'b1'));
console.log(getNewValue('b'));
CodePudding user response:
Array.prototype.find() should do the trick!
var value = "a1"
data.forEach(e => {
if (e.column === "a")
foundValue = e.children.find(c =>
c.column === value
)
})
wantedValue = foundValue.area.selectedValue || foundValue.area.defaultValue
console.log(wantedValue)
