gpt4 book ai didi

javascript - 如何在 javascript 中使用嵌套对象展平对象

转载 作者:行者123 更新时间:2023-12-05 09:10:31 25 4
gpt4 key购买 nike

我有一些来自父对象内部的嵌套对象的属性,但我想将嵌套对象与要展平的父对象合并。

原始对象:

enrollment = {
user: {
id: 'string',
name: 'string'
},
finished: 'boolean',
path: 'string'
}

预期的展平对象:

user: {
id: 'string',
name: 'string',
finished: 'boolean',
path: 'string'
}

最佳答案

您可以递归构建任意数量的嵌套对象。因此,此函数与您的情况无关:

var enrollment = {
user: {
id: 'string',
name: 'string'
},
finished: 'boolean',
path: 'boolean'
}

var enrollment2 = {
user: {
id: 'string',
name: 'string'
},
test: {
test1: {
test2: {
val0:'val0',
test4: { //3rd level nested object for example
val1: 'val1',
val2: 'val2'
}
}
}
},
finished: 'boolean',
path: 'boolean'
}

const flat = (obj, out) => {
Object.keys(obj).forEach(key => {
if (typeof obj[key] == 'object') {
out = flat(obj[key], out) //recursively call for nesteds
} else {
out[key] = obj[key] //direct assign for values
}

})
return out
}

console.log(flat(enrollment, {}))
console.log(flat(enrollment2, {}))

关于javascript - 如何在 javascript 中使用嵌套对象展平对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61333126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com