【问题标题】:Converting an array of data to JSON using a property map使用属性映射将数据数组转换为 JSON
【发布时间】:2023-04-10 09:39:01
【问题描述】:

我正在尝试使用键映射将二维数组转换为 json 对象。 键映射看起来像

var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];

数据是

var data = [
  [1, 'Task 1', 'C1', 'Customer 1', '999', '8888'],
  [2, 'Task 2', 'C2', 'Customer 2', '333', '5555']
];

输出 JSON 应该是

    var output = [
   {
      "id":1,
      "title":"Task 1",
      "customer":{
         "id":"C1",
         "name":"Customer 1",
         "phone":{
            "home":"999",
            "mobile":"8888"
         }
      }
   },
   {
      "id":2,
      "title":"Task 2",
      "customer":{
         "id":"C2",
         "name":"Customer 2",
         "phone":{
            "home":"333",
            "mobile":"5555"
         }
      }
   }
];

我正在尝试做类似的事情,但我在这里不擅长做 smerecursion 等。有人可以帮忙吗?

function arrToJSON(headers, data){
  var output = [];
  data.forEach(row, index){
    var cObj = {};
    headers.forEach(header, itemIndex){
      var headerParts = header.split('.');
      // NOt sure what to do here
    }
  }
}

【问题讨论】:

    标签: javascript arrays json data-manipulation


    【解决方案1】:

    你可以在js中使用mapreduce轻松实现结果。

    createObj(acc, curr.split("."), 0, o[index]);
    

    是递归中使用的函数,这就是您要查找的函数。

    Arguments

    createObj(
          acc,                  // object in which you want to add value
          curr.split("."),      // send path as an array
          0,                    // current index in path, initially zero
          o[index]              // value to be assigned
        );
    

    var keys = [
      "id",
      "title",
      "customer.id",
      "customer.name",
      "customer.phone.home",
      "customer.phone.mobile",
    ];
    
    var data = [
      [1, "Task 1", "C1", "Customer 1", "999", "8888"],
      [2, "Task 2", "C2", "Customer 2", "333", "5555"],
    ];
    
    function createObj(obj, arr, index, value) {
      if (index === arr.length - 1) obj[arr[index]] = value;
      else {
        if (!obj[arr[index]]) obj[arr[index]] = {};
        createObj(obj[arr[index]], arr, index + 1, value);
      }
    }
    
    const result = data.map((o) => {
      return keys.reduce((acc, curr, index) => {
        createObj(acc, curr.split("."), 0, o[index]);
        return acc;
      }, {});
    });
    
    console.log(result);
    /* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
    
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }

    【讨论】:

    • 感谢您的天才方法。我从没想过使用reduce方法。
    【解决方案2】:

    您可以简单地将解构和扩展运算符与 reduce 一起使用。

    var data = [
      [1, "Task 1", "C1", "Customer 1", "999", "8888"],
      [2, "Task 2", "C2", "Customer 2", "333", "5555"],
    ];
    
    const buildObject = (arr = []) => {
      return arr.reduce((acc, [id, title, cid, name, home, mobile]) => {
        const row = {
          id,
          title,
          customer: { id: cid, name, phone: { home, mobile } },
        };
        return acc.concat(row);
      }, []);
    };
    
    console.log(buildObject(data));

    【讨论】:

      猜你喜欢
      • 2017-06-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多