gpt4 book ai didi

javascript - 转换包含对象的对象

转载 作者:数据小太阳 更新时间:2023-10-29 04:26:42 26 4
gpt4 key购买 nike

我有以下键/值对象

form: {
id: {value: this.item.id, hidden: true},
title: {value: this.item.title},
translations: {
en: {
locale: {value: 'en', hidden: true},
name: {value: 'Hello World'}
},
nl: {
locale: {value: 'nl', hidden: true},
name: {value: 'Hallo Wereld'}
}
}
}

所以每个键都有一个带有值和隐藏属性的对象,我一直在研究如何实现以下目标。转换嵌套对象,使每个键都有它的值。不是具有值(value)和隐藏的对象。对我来说最大的问题是它是嵌套的..所以它必须递归工作。

这是期望的最终结果

form: {
id: this.item.id,
title: this.item.title,
translations: {
en: {
locale: 'en',
name: 'Hello World'
},
nl: {
locale: 'nl',
name: 'Hallo Wereld'
}
}
}

我试过了

使用 Object.keys(form).map(...) 的组合,它为我提供了每个项目的键,但恐怕这不会递归工作。

最佳答案

function transform(obj) {
return Object.entries(obj).reduce((newObj, [name, value]) => ({ ...newObj, [name]: value.value === undefined ? transform(value) : value.value }), {})
}

const form = {
id: {value: '77777', hidden: true},
title: {value: '11111'},
translations: {
en: {
locale: {value: 'en', hidden: true},
name: {value: 'Hello World'}
},
nl: {
locale: {value: 'nl', hidden: true},
name: {value: 'Hallo Wereld'}
}
}
}

console.log(transform(form))

解释:

function transform(obj) {
const entries = Object.entries(obj) // transform object to Array<[propertyName, propertyValue]>

const tranformedObject = entries.reduce(reducer, {}) // inital value for the first arg of reducer is {}

return tranformedObject
}

function reducer(newObj, [propertyName, propertyValue]) { // name
return {
...newObj, // get all properties (that we already set) from prev newObj
[propertyName]: propertyValue.value === undefined ? transform(propertyValue) : propertyValue.value // if property has .value use it or use recursively tranformed object
} // returned value will be set to newObj, and than returned to tranformedObject
}

{ ...prop, [name]: vaue } - 它是 ES6 syntax

关于javascript - 转换包含对象的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55122094/

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