簡體   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