[英]flattening the nested object in javascript
I ran into this problem, I was able to write solution which can handle array of object (not posted here) or one level deep nested object but i couldn't solve when the given object has nested structure like below.我遇到了这个问题,我能够编写可以处理对象数组(未在此处发布)或一级深度嵌套对象的解决方案,但是当给定对象具有如下嵌套结构时我无法解决。 I am curious to know how we can solve this.我很想知道我们如何解决这个问题。
const source = {
a: 1,
b: {
c: true,
d: {
e: 'foo'
}
},
f: false,
g: ['red', 'green', 'blue'],
h: [{
i: 2,
j: 3
}]
};
solution should be解决方案应该是
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
};
attempt for one deep nested object尝试一个深层嵌套对象
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);
}
calling the function调用函数
nestetdObject(source, '')
But my attempt will fail if the object is like { foo: { boo : { doo : 1 } } }
.但是如果对象像{ foo: { boo : { doo : 1 } } }
,我的尝试将失败。
You should be able to do it fairly simply with recursion.您应该能够通过递归相当简单地做到这一点。 The way it works, is you just recursively call a parser on object children that prepend the correct key along the way down.它的工作方式是,您只需递归调用对象子项上的解析器,并在向下的过程中预先添加正确的键。 For example (not tested very hard though):例如(虽然没有经过非常严格的测试):
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))
I am very late to the party but it can be easily achieved with a module like Flatify-obj .我参加聚会很晚,但可以使用像Flatify-obj这样的模块轻松实现。
Usage:用法:
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));
one more simple example with Object.keys
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.