3 回答
TA贡献1863条经验 获得超2个赞
您可以使用递归来扁平化您的对象,例如
let obj = {
"a": "aa",
"**b**": {
"**b**": "bb",
"c": 1,
},
"d": "d",
"*e*": {
"**e**": {
"e": 2
}
}
}
let flatten = (obj, final = {}) => {
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === 'object') {
flatten(value, final)
} else {
final[key] = value
}
})
return final
}
console.log(flatten(obj))
TA贡献1798条经验 获得超7个赞
在条目上使用forEach并构建新对象。如果值是对象,则用于Object.assign展平。
const obj = {
a: "aa",
b: {
b: "bb",
c: 1
},
d: "d"
};
const flatten = obj => {
const res = {};
Object.entries(obj).forEach(([key, value]) => {
if (typeof value === "object") {
Object.assign(res, value);
} else {
res[key] = value;
}
});
return res;
};
console.log(flatten(obj));
TA贡献1865条经验 获得超7个赞
我已经使用以下方式解决了它。
let finalArr = [];
for (let [key, value] of Object.entries(resObj)) {
if (typeof value === 'object') {
for (let [keyInternal, valueInternal] of Object.entries(value)) {
valueInternal.map(arrValue => {
const finalObj = {
a: '',
d: ''
};
finalObj.a= key;
finalObj.d= keyInternal;
var tempobj = {...finalObj,...arrValue};
finalArr.push(tempobj);
});
}
}
}
添加回答
举报