繁体   English   中英

使用Javascript展平父子JSON数组

[英]Flattening Parent Child JSON Array with Javascript

我有一个如下所示的数组。

const arr = [{
  name: 'x',
  type: 'type1',
  parent: [{
    name: "a",
    type: 'type1'
  }]
}, {
  name: 'y',
  type: 'type1',
  parent: [{
    name: "b",
    type: 'type1'
  }]
}];

我想压扁这个并最终看到如下结果:

const arr = [{
  name: 'x',
  type: 'type1',
  parent-name:'a',
  parent-type: 'type1'
  },
  {
  name: 'y',
  type: 'type1',
  parent-name: 'b',
  parent-type: 'type1'
}];

我已经尝试了使用map和array.prototype.flat()的各种不同的解决方案,但不能安静地让它工作。 我将永远不会有一个以上的孩子,如果有第二个孩子,那么我很好,因为它创造了2行。

谢谢迈克尔

一种方法是使用Map()

result = arr.map(obj => {
  obj.parent.forEach(item => {
    Object.keys(item).forEach(value => {
     obj["parent-" + value] = item[value];
    });
  });

  delete obj.parent;

  return obj;
});

实例:

 const arr = [{ name: 'x', type: 'type1', parent: [{ name: "a", type: 'type1' }] }, { name: 'y', type: 'type1', parent: [{ name: "b", type: 'type1' }] }] result = arr.map(obj => { obj.parent.forEach(item => { Object.keys(item).forEach(value => { obj["parent-" + value] = item[value]; }); }); delete obj.parent; return obj; }); console.log(result); 

如你所知,这会将任何JSON数组压平到第2级。

Object.flatten = function(data){
    var resultMain = [];
    var result = {};
    function recurse(cur, prop){
        if (Object(cur) !== cur){
            result[prop] = cur;
        }else if(Array.isArray(cur)){
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop);
            if(l == 0)
                result[prop] = [];
        }else{
            var isEmpty = true;
            for(var p in cur){
                isEmpty = false;
                recurse(cur[p], prop ? prop+"-"+p : p);
            }
            if(isEmpty && prop)
                result[prop] = {};
        }
    }
    for(var i=0; i<data.length; i++){
        result = {};
        recurse(data[i], "");
        resultMain[i] = result;
    }
    return resultMain;
}

Object.flatten()在行动中:

 const arr = [{ name: 'x', type: 'type1', parent: [{ name: "a", type: 'type1' }] }, { name: 'y', type: 'type1', parent: [{ name: "b", type: 'type1' }] }]; Object.flatten = function(data){ var resultMain = []; var result = {}; function recurse(cur, prop){ if (Object(cur) !== cur){ result[prop] = cur; }else if(Array.isArray(cur)){ for(var i=0, l=cur.length; i<l; i++) recurse(cur[i], prop); if(l == 0) result[prop] = []; }else{ var isEmpty = true; for(var p in cur){ isEmpty = false; recurse(cur[p], prop ? prop+"-"+p : p); } if(isEmpty && prop) result[prop] = {}; } } for(var i=0; i<data.length; i++){ result = {}; recurse(data[i], ""); resultMain[i] = result; } return resultMain; } console.log(Object.flatten(arr)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM