gpt4 book ai didi

javascript - 基于字符串创建具有动态属性名称的对象

转载 作者:行者123 更新时间:2023-11-28 17:05:26 25 4
gpt4 key购买 nike

我有这个对象数组:

[
{
"id": 4,
"user_id": 1,
"business_id": 2,
"branch_id": 3,
"type": "service",
"item": "Typing",
"unitPrice": 100,
"bulkUnit": 20,
"bulkUnitPrice": 80,
"availableUnits": "NA",
"created_at": "2019-05-03 11:36:33",
"updated_at": "2019-05-03 11:36:33"
},
{
"id": 5,
"user_id": 1,
"business_id": 2,
"branch_id": 3,
"type": "service",
"item": "Printing",
"unitPrice": 70,
"bulkUnit": 50,
"bulkUnitPrice": 40,
"availableUnits": "NA",
"created_at": "2019-05-03 11:37:29",
"updated_at": "2019-05-03 11:37:29"
}
]

对于每个对象,我需要使用 item 属性的值作为新对象中的属性名称,如下所示:

{
"Typing": null,
"Printing": null
}

最佳答案

您可以使用 Array.prototype.map() 的组合来实现此目的和 Object.fromEntries() .

const data = [
{"id":4,"user_id":1,"business_id":2,"branch_id":3,"type":"service","item":"Typing","unitPrice":100,"bulkUnit":20,"bulkUnitPrice":80,"availableUnits":"NA","created_at":"2019-05-03 11:36:33","updated_at":"2019-05-03 11:36:33"},
{"id":5,"user_id":1,"business_id":2,"branch_id":3,"type":"service","item":"Printing","unitPrice":70,"bulkUnit":50,"bulkUnitPrice":40,"availableUnits":"NA","created_at":"2019-05-03 11:37:29","updated_at":"2019-05-03 11:37:29"}
];

const result = Object.fromEntries(data.map(x => [x.item, null]));
console.log(result)

关于javascript - 基于字符串创建具有动态属性名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55973964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com