簡體   English   中英

在javascript中展平嵌套對象

[英]flattening the nested object in javascript

我遇到了這個問題,我能夠編寫可以處理對象數組(未在此處發布)或一級深度嵌套對象的解決方案,但是當給定對象具有如下嵌套結構時我無法解決。 我很想知道我們如何解決這個問題。

const source = {
  a: 1,
  b: {
    c: true,
    d: {
      e: 'foo'
    }
  },
  f: false,
  g: ['red', 'green', 'blue'],
  h: [{
    i: 2,
    j: 3
  }]
};

解決方案應該是

const solution = {
    'a': 1,
    'b.c': true,
    'b.d.e': 'foo',
    'f': false,
    'g.0': 'red',
    'g.1': 'green',
    'g.2': 'blue',
    'h.0.i': 2,
    'h.0.j': 3
};

嘗試一個深層嵌套對象

let returnObj = {}

let nestetdObject = (source, parentKey) => {

    let keys = keyFunction(source);

    keys.forEach((key) => {
      let values = source[key];

      if( typeof values === 'object' && values !== null ) {
        parentKey = keys[0]+'.'+keyFunction(values)[0]
        nestetdObject(values, parentKey);
      }else{
        let key = parentKey.length > 0 ? parentKey : keys[0];
        returnObj[key] = values;
      }
    })
    return returnObj
};

// Key Extractor 
let keyFunction = (obj) =>{
  return Object.keys(obj);
}

調用函數

nestetdObject(source, '')

但是如果對象像{ foo: { boo : { doo : 1 } } } ,我的嘗試將失敗。

您應該能夠通過遞歸相當簡單地做到這一點。 它的工作方式是,您只需遞歸調用對象子項上的解析器,並在向下的過程中預先添加正確的鍵。 例如(雖然沒有經過非常嚴格的測試):

 const source = { a: 1, b: { c: true, d: { e: 'foo' } }, f: false, g: ['red', 'green', 'blue'], h: [{ i: 2, j: 3 }] } const flatten = (obj, prefix = '', res = {}) => Object.entries(obj).reduce((r, [key, val]) => { const k = `${prefix}${key}` if(typeof val === 'object'){ flatten(val, `${k}.`, r) } else { res[k] = val } return r }, res) console.log(flatten(source))

我參加聚會很晚,但可以使用像Flatify-obj這樣的模塊輕松實現。

用法:

   const flattenObject = require('flatify-obj');

   flattenObject({foo: {bar: {unicorn: '🦄'}}})
   //=> { 'foo.bar.unicorn': '🦄' }

   flattenObject({foo: {unicorn: '🦄'}, bar: 'unicorn'}, {onlyLeaves: true});
   //=> {unicorn: '🦄', bar: 'unicorn'}

 // Licensed under CC0 // To the extent possible under law, the author(s) have dedicated all copyright // and related and neighboring rights to this software to the public domain // worldwide. This software is distributed without any warranty. const source = { a: 1, b: { c: true, d: { e: "foo" } }, f: false, g: ["red", "green", "blue"], h: [{ i: 2, j: 3 }], }; function flatten(source, parentKey, result = {}) { if (source?.constructor == Object || source?.constructor == Array) { for (const [key, value] of Object.entries(source)) { flatten( value, parentKey != undefined ? parentKey + "." + key : key, result ); } } else { result[parentKey] = source; } return result; } console.log(flatten(source));

Object.keys一個更簡單的例子

 const apple = { foo: { boo : { doo : 1 } } } let newObj = {} const format = (obj,str) => { Object.keys(obj).forEach((item)=>{ if(typeof obj[item] ==='object'){ const s = !!str? str+'.'+item:item format(obj[item],s) } else { const m = !!str?`${str}.`:'' newObj[m+item]= obj[item] } }) } format(apple,'') console.log(newObj)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM