gpt4 book ai didi

javascript - 如何将多个对象串行推送到一个对象中

转载 作者:行者123 更新时间:2023-11-30 08:19:18 25 4
gpt4 key购买 nike

我在一个变量中有 2 个或多个对象,我想将这些对象放入一个对象中。

let a = {"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}

{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}

我希望输出为:

{
"0": {
"device_type": "iphone",
"filter_data": {
"title": {
"value": "Lorem Ipsum..",
"data": {}
},
"message": {
"value": "Lorem Ipsum is simply dummy text of the printing...",
"data": {}
},
"dismiss_button": {
"value": "Ok",
"data": {}
},
"action_url": {
"value": "",
"data": {
"type": "custom"
}
}
}
},
"1": {
"device_type": "iphone",
"filter_data": {
"message": {
"value": "Push Message goes here.",
"data": {}
}
}
}
}

我该怎么做?

最佳答案

您可以将 }{ 替换为 },{,解析它并获取 Object.assign用于从数组中获取具有索引作为属性的对象。

const
data = '{"device_type":"iphone","filter_data":{"title":{"value":"Lorem Ipsum..","data":{}},"message":{"value":"Lorem Ipsum is simply dummy text of the printing...","data":{}},"dismiss_button":{"value":"Ok","data":{}},"action_url":{"value":"","data":{"type":"custom"}}}}{"device_type":"iphone","filter_data":{"message":{"value":"Push Message goes here.","data":{}}}}';
result = Object.assign({}, JSON.parse(`[${data.replace(/\}\{/g, '},{')}]`));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: auto; }

关于javascript - 如何将多个对象串行推送到一个对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660932/

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