简体   繁体   English

如何在对象数组中插入 object

[英]How can I insert an object in an array of objects

I want to convert my object status field that is would be modified specifically.我想转换我的 object 状态字段,该字段将被专门修改。 I have found the answer but no fill my goal that's why I updated my question我找到了答案,但没有完成我的目标,这就是我更新问题的原因

I have objects like this below:我在下面有这样的对象:

   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": 6,
    "alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
    "name": "Test",
    "status": 3
  }
]

I need to convert my object like below or I need to print like belows:我需要像下面那样转换我的 object 或者我需要像下面这样打印:

    [
  {
    "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"
    }
  },
  {
    "id": 6,
    "alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98",
    "name": "Test",
    "status": {
      "3": "DELETED"
    }
  }
]

For example:例如:

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

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

Update: addded lookup via possibleStatus更新:通过possibleStatus添加了查找


If nullish coalescing operator ??如果无效合并运算符?? is available, I would add a fallback for undefined status:可用,我会为未定义的状态添加一个后备:

Items.map(item => ({...item, status: {[item.status]: possibleStatus[item.status] ?? `UNDEFINED STATUS ${item.status}`}}))

but only if this is display logic.但前提是这是显示逻辑。 In case of business logic, I'd rather check for valid values and throw an exception, eg encapsulated in a function mapping the status string to the object.在业务逻辑的情况下,我宁愿检查有效值并抛出异常,例如封装在 function 中,将状态字符串映射到 object。

 let statusTable = { 1: "ACTIVE", 2: "INACTIVE", 3: "DELETED" } 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 }, { "id": 6, "alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98", "name": "Test", "status": 3 } ] let result = Items.map(el => { el.status = { [el.status]: statusTable[el.status] } return el; }) console.log(result);

If this is json, first you might want to parse it with JSON.parse, like following:如果这是 json,首先你可能想用 JSON.parse 解析它,如下所示:

let parse = JSON.parse(yourJsonObj)

Next you get your array, which you need to modify.接下来,您将获得需要修改的数组。 You can use map method and return a new array with the data you need:您可以使用 map 方法并返回包含所需数据的新数组:

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

Then you can go back and stringify it back if needed with JSON.stringify(newData).然后,您可以返回 go 并在需要时使用 JSON.stringify(newData) 将其字符串化。

The rules by which you set INACTIVE or ACTIVE I don't know, but this is the gist of it.你设置 INACTIVE 或 ACTIVE 的规则我不知道,但这是它的要点。

I hope this solution be useful for you.我希望这个解决方案对你有用。

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

Items = Items.map(item => {
item.status = item.status == 1 ?  { "1": "ACTIVE" } : { "2": "INACTIVE" }
return item;
} )

console.log(Items);

As others have indicated, map() is the way to go.正如其他人指出的那样, map()是通往 go 的方式。

I've stepped things out a little here in such a way that the system wouldn't have unintended consequences if a third property was introduced.我在这里做了一些改动,这样如果引入了第三个属性,系统就不会产生意想不到的后果。 The switch statement explicitly only changes things if the status is 1 or 2 and leaves things alone otherwise. switch 语句仅在状态为 1 或 2 时显式地改变事物,否则不做任何事情。

The other examples given are probably fine for your use case though.不过,给出的其他示例可能适合您的用例。

 var 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": 6, "alias": "ed8a921-c2c2-4a49-8893-5bf5c2bc0d98", "name": "Test", "status": 3 } ]; const process = () => { // render original const orig = document.querySelector('.original'); orig.innerHTML = ''; items.forEach(i => orig.innerHTML += `<li>${i.status}</li>`); var result = items.map(i => { switch(i.status) { case(1): i.status = {"1": "ACTIVE"} break; case(2): i.status = {"2": "INACTIVE"} break; case(3): i.status = {"3": "DELETED"} break; default: // if status is not 1, 2 or 3, do nothing to the object break; } // return the object return i }) // render processed const res = document.querySelector('.results'); res.innerHTML = ''; items.forEach(i => res.innerHTML += `<li>${JSON.stringify(i.status)}</li>`); } process()
 <div class="cols"> <div> <p>Original</p> <ul class="original"> </ul> </div> <div> <p>Result</p> <ul class="results"></ul> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript:如何将对象插入到对象数组中? - JavaScript: How can I insert an Object into an Array of Objects? 如何使用 Node JS 将对象数组中的 object 的属性插入 SQLServer? - How can I insert attributes of an object from an array of objects into SQLServer using Node JS? 如何将对象的这个对象转换为对象的数组? - How can I convert this object of objects into an array of objects? 如何将单个对象对象转换为对象数组? - How can I convert a single Object of objects, into an array of objects? 如果数组对象的 2 个属性相等,我如何删除数组中的对象? - How can i remove the object in the array if 2 properties of array objects are equal? 如何将值插入数组的 object 属性? - How can I insert values to an object property of an array? 如何在对象数组中组合类似的对象并插入新的 object? - How to combine like objects within array of objects and insert new object? 如何将具有相同键的对象数组合到一个对象中? - How can I combine an array of objects with the same keys into one object? 如何使用另一个对象中的值过滤对象数组? - How can I filter an array of objects with a value from another object? 我如何从对象数组中获取对象 - How can i get an object from an array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM