typescript 从JSON数组中删除特定数据

b5lpy0ml  于 2022-12-27  发布在  TypeScript
关注(0)|答案(4)|浏览(205)

我有一个Json,它有一些ID为null的数据,我想要的是移除ID为null的项。请建议最佳方法。所以在itemProperty中,我想要移除ID为null的两个项

{ 
itemProperties :
 { 
   itemProperty: [
   {
    id:"23", 
    name: "asd"
   },
   {
    id:"232", 
    name: "asd1"
   },
   {
    id:null, 
    name: "asd2"
   },
   {
    id:"2932", 
    name: "asd3"
   },
   {
    id:null, 
    name: "asd4"
   }

 ]} }
t5fffqht

t5fffqht1#

您可以在js数组上使用.filter方法,如下所示。

itemProperty.filter((item) => item.id !== null)

这将返回仅具有通过测试的项的过滤数组。

bn31dyow

bn31dyow2#

你可以试试这个,

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

操作员:

[
 {
  id: "23",
  name: "asd"
 }, {
  id: "232",
  name: "asd1"
 }, {
  id: "2932",
  name: "asd3"
 }
]
bksxznpy

bksxznpy3#

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

ui7jx7zq4#

下面是对象中scaffold的数据!但是我更新了数据格式

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

相关问题