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
CodePudding user response:
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);
CodePudding user response:
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);