Home > database >  Return string from an attribute in array of objects
Return string from an attribute in array of objects

Time:02-03

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 find to get a match on the column.
  • Use ?. optional-chaining to refer children within the matched object
  • .find the matching value (such as a1, or a2, etc) within children
  • return either the selectedValue or defaultValue or, 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)
  •  Tags:  
  • Related