简体   繁体   中英

filter data from array of objects based on selected value

I have a component which is showing data from an array:

my first component:

firstArr = [
  {
    "code": "firstArr item 1",
    "name": "firstArr item 1"
  },
  {
    "code": "firstArr item 2",
    "name": "firstArr item 2"
  },
  {
    "code": "firstArr item 3",
    "name": "firstArr item 3"
  },
]

<FirstComponent
  data={firstArr}
  onUpdate={selectedValue => {
    setval(selectedValue);
    console.log(selectedValue);
  }}
/>

Now I have another list:

list2 = {
  "firstArr item 1": [
      {
          "code": "firstArr Subitem 1",
          "name": "firstArr Subitem 1"
      }
  ],
  "firstArr item 2": [
      {
          "code": "firstArr Subitem 2",
          "name": "firstArr Subitem 2"
      }
  ],
  "firstArr item 3": [
      {
          "code": "firstArr Subitem 3",
          "name": "firstArr Subitem 3"
      }
  ],
}

Now based on selectedValue from firstArr , I need to filter list2 and show only sub items of selectedValue

I tried:

var dataNew = list2.filter(function (i) {
  return i = "firstArr item 1"
})

But this is giving error

You can use Object.keys for this:

var firstArr = [
  {
    code: "firstArr item 1",
    name: "firstArr item 1"
  },
  {
    code: "firstArr item 2",
    name: "firstArr item 2"
  },
  {
    code: "firstArr item 3",
    name: "firstArr item 3"
  }
];

var list2 = {
  "firstArr item 1": [
    {
      code: "firstArr Subitem 1",
      name: "firstArr Subitem 1"
    }
  ],
  "firstArr item 2": [
    {
      code: "firstArr Subitem 2",
      name: "firstArr Subitem 2"
    }
  ],
  "firstArr item 3": [
    {
      code: "firstArr Subitem 3",
      name: "firstArr Subitem 3"
    }
  ]
};

var dataNew = Object.keys(list2)
  .filter((x) => x === "firstArr item 1")
  .map((i) => {
    return list2.find((x) => x.code === i);
  });

console.log(dataNew);

It might be easier to use a loop for this.

This example assumes that the array only contains one object, and you only need the properties from that array to populate the new select. If you need the whole array just remove the [0] from list[key][0] .

 const list={"firstArr item 1":[{code:"firstArr Subitem 1",name:"firstArr Subitem 1"}],"firstArr item 2":[{code:"firstArr Subitem 2",name:"firstArr Subitem 2"}],"firstArr item 3":[{code:"firstArr Subitem 3",name:"firstArr Subitem 3"}]}; const value = 'firstArr item 2'; let out; for (const key in list) { if (key === value) out = list[key][0]; } console.log(out);

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