I have a Json having few data with ID null, what i want is to remove the items having id null. Please suggest the best approach. so in itemProperty i want to remove two items where id is null
{
itemProperties :
{
itemProperty: [
{
id:"23",
name: "asd"
},
{
id:"232",
name: "asd1"
},
{
id:null,
name: "asd2"
},
{
id:"2932",
name: "asd3"
},
{
id:null,
name: "asd4"
}
]} }
CodePudding user response:
you can use the .filter
method on a js array as shown below.
itemProperty.filter((item) => item.id !== null)
this will return the filtered array with only the items that pass the test.
CodePudding user response:
const jsonObj = {
itemProperties : {
itemProperty: [
{
id:"23",
name: "asd"
},
{
id:"232",
name: "asd1"
},
{
id:null,
name: "asd2"
},
{
id:"2932",
name: "asd3"
},
{
id:null,
name: "asd4"
}
]
}
}
const validItemProperty =
[...jsonObj.itemProperties.itemProperty].filter(i => i.id !== null )
const newJsonObj = {
itemProperties: {
itemProperty: validItemProperty
}
}
console.log(newJsonObj)
CodePudding user response:
Here is data in the scaffold in the object! But I update the data format
const itemProperty = [{
id: "23",
name: "asd"
},
{
id: "232",
name: "asd1"
},
{
id: null,
name: "asd2"
},
{
id: "2932",
name: "asd3"
},
{
id: null,
name: "asd4"
}
];
// Option One
// const data = itemProperty.filter((item) => item.id !== null);
// console.table(data)
// Option Two
function getData(data) {
return data
.filter((el) => el.id == null)
.map(({
id,
name
}) => ({
id,
name
}));
}
console.table(getData(itemProperty));
CodePudding user response:
You can try this,
var json_data = {
"itemProperties": {
"itemProperty": [
{
"id": "23",
"name": "asd"
},
{
"id": "232",
"name": "asd1"
},
{
"id": null,
"name": "asd2"
},
{
"id": "2932",
"name": "asd3"
},
{
"id": null,
"name": "asd4"
}
]
}
};
console.log(json_data.itemProperties.itemProperty.filter((item) => item.id !== null));
O/P :
[
{
id: "23",
name: "asd"
}, {
id: "232",
name: "asd1"
}, {
id: "2932",
name: "asd3"
}
]