[英]how to push multiple objects into one object serially
我在一個變量中有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; }
如果它們在數組中,則非常簡單-只需使用reduce
:
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":{}}}}]; const res = data.reduce((a, c, i) => (a[i] = c, a), {}); console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }
您可以使用Array.protoype.match
分隔每個對象,然后使用Array.protoype.reduce
獲得預期的對象。
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":{}}}}'; let objects = a.match(/({"device_type".*?}}}})/g).map(e => JSON.parse(e)); console.log('Array of objects',objects) const out = {...[objects]}; console.log('\\ndesired output',out)
同樣,當鍵只是索引時,將數組轉換為對象似乎沒有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.