简体   繁体   English

如何通过过滤嵌套属性返回父对象

[英]How to return parent object by filtering nested property

I am trying to filter an array with nested objects, but the parent isn't being returned when filtering on a child property. 我正在尝试使用嵌套对象过滤数组,但是在对子属性进行过滤时不会返回父对象。

let line = "xyz";

let data = [
    {
        "header": {
            "po_no": "P.O. Number"
        },
        "line": line
    },
    {
        "header": {
            "po_no": "Another P.O. Number"
        },
        "line": line
    }
];

... ...

data.filter(item => { 
  return item.header.po_no === 'P.O. Number' // Evaluates to true
})

I'd like to return the entire item when its header.po_no matches a string. header.po_no与字符串匹配时,我想返回整个item

I'm not sure how to debug this since it's not returning any values when the return condition evaluates to true. 我不确定如何调试它,因为当返回条件评估为true时,它不会返回任何值。

Expected output: 预期产量:

[{
  "header": {
    "po_no": "P.O. Number"
  },
  "line": line
}]

How can I return the entire array index when a sub-property is matching using a filter? 当使用过滤器匹配子属性时,如何返回整个数组索引?

.filter returns a new Array; .filter返回一个新的数组; it doesn't modify the array. 它不会修改数组。 So if you're expecting data to have that output, it won't. 因此,如果您期望data具有该输出,则不会。 However, this will: 但是,这将:

const expectedItems = data.filter(item => { 
  return item.header.po_no === 'P.O. Number' // Evaluates to true
});

You had ' quote type in your code. 您的代码中有'引用类型。 filtered data saved to variable. 过滤后的数据保存到变量。

let line = "xyz";

let data = [
  {
    "header": {
    "po_no": "P.O. Number"
    },
    "line": line
  }, 
  {
    "header": {
    "po_no": "Another P.O. Number"
  },
  "line": line
  }
];

const filtered = data.filter(item => { 
  return item.header.po_no === 'P.O. Number' // Evaluates to true
})

Using Array.filter with arrow function would solve this in the most concise way. Array.filter与箭头功能一起使用将以最简洁的方式解决此问题。 filter returns the main array and the filtered items where find would only return the specific item that matched. filter返回主数组和过滤后的项,而find只会返回匹配的特定项。

 let line = "xyz"; let data = [{ "header": { "po_no": "PO Number" }, line }, { "header": { "po_no": "Another PO Number" }, line } ]; let filter = data.filter(d => d.header.po_no === 'PO Number') // return arr let find = data.find(d => d.header.po_no === 'PO Number') // return just the item console.log(filter) console.log(find) 

When dealing with arrow functions and you have a direct return you do not need to open a function bracket ... just do: 当处理箭头函数并且您有直接收益时,您无需打开函数支架...只需执行以下操作:

data.filter(d => d.header.po_no === 'P.O. Number')  // <-- no { return ... }

Also note that since your property is called line you can simply define your object as: 还要注意,由于您的属性称为line您可以简单地将对象定义为:

  {
    "header": { "po_no": "Another P.O. Number" },
    line  // <-- same prop name as your variable name
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM