Return 来自对象数组中属性的字符串

Return string from an attribute in array of objects

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

这可能是获得所需 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';
}

说明

  • 使用 findcolumn 上进行匹配。
  • 使用?.optional-chaining在匹配的对象中引用children
  • .findchildren
  • 中的匹配值(如a1,或a2等)
  • return selectedValuedefaultValue 或者,如果两者都是假的,string-constant 以通知没有匹配项。

代码段

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'));

Array.prototype.find() 应该可以解决问题![​​=11=]

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)