我在一个变量中有 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/