[英]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
现在基于firstArr
中的selectedValue
,我需要过滤list2
并仅显示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:您可以为此使用Object.keys :
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]
.如果您需要整个数组,只需从list[key][0]
[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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.