我如何在对象数组中插入对象

问题描述 投票:0回答:3

我想转换将被修改的对象状态字段。

我下面有类似的对象:

   Items = [
  {
    "id": 9,
    "alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
    "name": "sfasf",
    "status": 1
  },
  {
    "id": 5,
    "alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
    "name": "Test",
    "status": 2
  }
]

我需要像下面那样转换我的对象

    [
  {
    "id": 9,
    "alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
    "name": "sfasf",
    "status": {
      "1": "ACTIVE"
    }
  },
  {
    "id": 5,
    "alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
    "name": "Test",
    "status": {
      "2": "INACTIVE"
    }
  }
]
javascript object
3个回答
1
投票

例如:

const possibleStatus = {
  1: 'ACTIVE',
  2: 'INACTIVE'
}

items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status]}}))

更新:通过possibleStatus添加的查找


0
投票

  let Items = [
  {
    "id": 9,
    "alias": "5cbe5c1c-e36b-422d-beb3-225a8e549bf1",
    "name": "sfasf",
    "status": 1
  },
  {
    "id": 5,
    "alias": "ed8a6921-c2c2-4a49-8893-5bf5c2bc0d98",
    "name": "Test",
    "status": 2
  }
]

let result = Items.map(el => {
   el.status = { [el.status]: el.status == 1 ? "ACTIVE" : "INACTIVE" }
   return el;
})

console.log(result);

0
投票

如果是json,首先您可能想用JSON.parse对其进行解析,如下所示:

let parse = JSON.parse(yourJsonObj)

接下来,您将获得需要修改的数组。您可以使用map方法并返回一个包含所需数据的新数组:

let newData = parse.map(item => {
  item.status = { "2": "INACTIVE" };
  return item;
});

然后,您可以根据需要使用JSON.stringify(newData)返回并对其进行字符串化。

我不知道设置无效或活动的规则,但这是要点。

© www.soinside.com 2019 - 2024. All rights reserved.