假设我有这样的json(使用JSON.stringify)
{名称:“ Bill”,姓氏:“ Smith”}
我想要用大括号括起来的值
{名称:{value:'Bill'},姓氏:{value:'Smith'}}
那么有什么想法可以使用javascript或lodash做到这一点?
答案 0 :(得分:1)
我将在输入上使用Object.entries
,映射到嵌套对象,然后调用Object.fromEntries
将其再次转换回去:
const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.fromEntries(
Object.entries(input).map(
([key, value]) => ([key, { value }])
)
);
console.log(newObj);
Object.fromEntries
是一种非常新的方法,因此对于较旧的浏览器,要么包含一个polyfill,要么使用类似.reduce
的东西:
const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.entries(input).reduce(
(a, [key, value]) => {
a[key] = { value };
return a;
},
{}
);
console.log(newObj);
答案 1 :(得分:0)
您可以使用for...in
遍历对象的键并像这样更新它:
const input = { name: 'Bill', lastname: 'Smith'};
for (const key in input) {
input[key] = { value: input[key] }
}
console.log(input)
如果您不想改变输入并想要创建一个新对象,请创建另一个对象并对其进行更新:
const input = { name: 'Bill', lastname: 'Smith'},
output = {}
for (const key in input) {
output[key] = { value: input[key] }
}
console.log(output)
答案 2 :(得分:0)
您可以使用lodash的_.mapValues()
返回具有转换后值的新对象:
const object = { name: 'Bill', lastname: 'Smith'};
const result = _.mapValues(object, value => ({ value }));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>