HJ1990
HJ1990

Reputation: 415

How to filter nested objects in Javascript

How would I use the filter() on nested items ? I am trying to retrieve all the data that has a projex.HeightPay === '1'. I would like to get back the Id, Name,System etc and the projex items if the HeightPay is 1.

For example:

  const fakeData = [
  {
    Id: "022173333101",
    Name: "Blue",
    System: "DESIGN",
    Squares: 0,
    Attributes: {
      projex: [
        {
          Project: "50",
          HeightPay: "1"
        },
        {
          Project: "50",
          HeightPay: "0"
        }
      ]
    },
    Customer: {
      Addr1: "Somewhere",
      Addr2: ""
    }
  }
];

// returns nothing
const found = fakeData.filter(data => data.Attributes.projex.HeightPay === "1");

Desired output:

  {
    Id: "022173333101",
    Name: "Blue",
    System: "DESIGN",
    Squares: 0,
    Attributes: {
      projex: [
        {
          Project: "50",
          HeightPay: "1"
        }
      ]
    },
    Customer: {
      Addr1: "Somewhere",
      Addr2: ""
    }
  }

Upvotes: 0

Views: 45

Answers (2)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You can use Array.prototype.map to go through each element of the fakeData array and then filter on the child array Attributes.projex using Array.prototype.filter and return a new object from the map call for every iteration

The new object in the Array.prototype.map call is formed by taking all the properties of each element of fakeData using the object spread operator ... except the Attributes.projex property and then assigning the new Attributes.projex array from the Array.prototype.filter to each new object:

const fakeData = [ { Id: "022173333101", Name: "Blue", System: "DESIGN", Squares: 0, Attributes: { projex: [ { Project: "50", HeightPay: "1" }, { Project: "50", HeightPay: "0" } ] }, Customer: { Addr1: "Somewhere", Addr2: "" } } ];

const found = fakeData.map(data => ({
  ...data,
  Attributes: {
    projex: data.Attributes.projex.filter(({
      HeightPay
    }) => HeightPay === "1")
  }
}));
console.log(found);

Upvotes: 1

Glech
Glech

Reputation: 781

const result = fakeData.map(item => ({
        ...item,
        Attributes: {
                projex: item.Attributes.projex.filter(e => e.HeightPay === "1")
        }
}))

Upvotes: 0

Related Questions