как вставить несколько объектов в один объект последовательно - PullRequest
0 голосов
/ 19 июня 2019

У меня есть 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 ]

2 голосов
/ 19 июня 2019

Вы можете заменить }{ на },{, проанализировать его и взять 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 голос
/ 19 июня 2019

Если они в массиве, это довольно просто - просто используйте 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; }
0 голосов
/ 19 июня 2019

Вы можете использовать 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)

Кроме того, представляется бесполезным преобразовывать массив в объект, когда ключи являются только индексами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...