平坦化深嵌套对象


let obj = {
name: "Allen",
age: 26,
address: {
city: "city1",
dist: "dist1",
state: "state1"
},
grandParent: {
parent: {
key1: "val1",
key2: "val2",
innerParent: {
innerParentKey1: "innerParentVal1",
innerParentKey2: "innerParentKey2",
innerParentKey3: "innerParentVal3"
}
},
child: {
childKey1: 'childVal1',
childKey2: 'childVal2',
childKey3: 'childVal3'
}
}
}

我想要平化上面的对象,结果应该像下面的输出:对象也可以包含数组,但我只需要平化对象

obj2 = {
"name": "Allen",
"age": 26,
"address/city": "city1",
"address/dist": "dist1",
"address/state": "state1",
"grandParent/parent/key1": "val1",
"grandParent/parent/key2": "val2",
"grandParent/parent/innerParent/innerParentKey1": "innerParentVal1",
"grandParent/parent/innerParent/innerParentKey2": "innerParentKey2",
"grandParent/child/childKey1": "childVal1",
"grandParent/child/childKey2": "childVal2",
"grandParent/child/childKey3": "childVal3",
}
有谁能帮我一下吗?

const flattenObj = (object) => {
let finalObject = {};
for (let i in object) {
if (!object.hasOwnProperty(i)) continue;
if (object[i] !== null && (typeof object[i]) == 'object') {
let newObject = flattenObj(object[i]);
for (let j in newObject) {
if (!newObject.hasOwnProperty(j)) continue;
finalObject[i + '/' + j] = newObject[j];
}
} else {
finalObject[i] = object[i];
}
}
return finalObject;
}
let obj = {
name: "Allen",
age: 26,
address: {
city: "city1",
dist: "dist1",
state: "state1"
},
grandParent: {
parent: {
key1: "val1",
key2: "val2",
innerParent: {
innerParentKey1: "innerParentVal1",
innerParentKey2: "innerParentKey2",
innerParentKey3: "innerParentVal3"
}
},
child: {
childKey1: 'childVal1',
childKey2: 'childVal2',
childKey3: 'childVal3'
}
}
}
console.log(flattenObj(obj))

最新更新