简体   繁体   中英

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.

I'm not sure how to debug this since it's not returning any values when the return condition evaluates to 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; it doesn't modify the array. So if you're expecting data to have that output, it won't. 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. filter returns the main array and the filtered items where find would only return the specific item that matched.

 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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