gpt4 book ai didi

javascript - 如何用大括号(包括子数组)包裹 json 的值?

转载 作者:行者123 更新时间:2023-11-28 03:41:03 25 4
gpt4 key购买 nike

基于这篇文章How can I wrap the value of json with curly braces?

在嵌套结构中附加“值”怎么样?

{ name: 'Bill', lastname: 'Smith', child: { name: 'Adam', options: [{ option: "1" }, { option: "2" }] } }

结果应该是

{ name: { value:'Bill'}, lastname: { value:'Smith'},
child: {
name: { value:'Adam'},
options: [{
option: { value:'1'}
},
{ option: { value:'2'}
}]
}
...
}

最佳答案

递归地运行它并为数组和对象添加特殊处理。

const input = { name: 'Bill', lastname: 'Smith', child: { name: 'Adam', options: [{ option: "1" }, { option: "2" }] } };
const transform = (input) => Object.fromEntries(
Object.entries(input).map(([key, value]) => {
// If it is an array, transform each object in it
if(Array.isArray(value)) {
return ([key, value.map(el => transform(el))]);
}
// If it is an object, transform its value
else if(typeof value === 'object' && value !== null) {
return [key, transform(value)];
}
// If it is a normal value, add the {value: } part
else {
return ([key, { value }]);
}
})
);

console.log(transform(input));

关于javascript - 如何用大括号(包括子数组)包裹 json 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57307342/

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