如何将多个对象依次推入一个对象

时间:2019-06-19 06:01:12

标签: javascript arrays json object

我在一个变量中有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": {}
      }
    }
  }
}

我该怎么做?

3 个答案:

答案 0 :(得分:2)

您可以将}{替换为},{,进行解析,然后使用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; }

答案 1 :(得分:1)

如果它们在数组中,则非常简单-只需使用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; }

答案 2 :(得分:0)

您可以使用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)

此外,当键只是索引时,将数组转换为对象似乎没有用。