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

标签 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": {}
      }
    }
  }
}

我该怎么做?

最佳答案

您可以将 }{ 替换为 },{,解析它并获取 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/

相关文章:

javascript - olx.com 如何显示类别更改的表单字段并相应提交?

json - Alamofire:通过成功响应处理错误

javascript - 如何将 Firebase 用作具有生成键(JS)的关系数据库?

javascript - 在 Node.js 7 中,抑制 UnhandledPromiseRejectionWarning 的正确方法是什么?

ios - Swift - 获取从今天开始的最后 7 天数组

arrays - Bash - 在 macOS 上返回空数组

javascript - 按条件 Javascript 对数组进行分块

java - com.fasterxml.jackson.databind.JsonMappingException : Can not deserialize instance of org. springframework.data.domain.Sort out START_ARRAY token

javascript - 仅在较小屏幕上加载 jquery - 在调整大小和页面加载时

javascript - 更改新 Javascript 框架中的语法