1

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"
   }

 ]} }
1
  • You should always include your implementation Commented Dec 26, 2022 at 6:41

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Here is data in the scaffold in the object!
1

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"
 }
]

Comments

0

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)

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.