如何用花括号包装json的值? [英] How can I wrap the value of json with curly braces?

查看:81
本文介绍了如何用花括号包装json的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的json(使用JSON.stringify)

Let say I have json like this (use JSON.stringify)

{名称:"Bill",姓氏:"Smith"}

{ name: 'Bill', lastname: 'Smith'}

我想要用大括号括起来的值

And I want the value wrapped with curly braces like this

{名称:{value:'Bill'},姓氏:{value:'Smith'}}

{ name: { value: 'Bill' }, lastname: { value: 'Smith'} }

那么有什么想法可以使用javascript或lodash做到这一点?

So any idea to do like this using javascript or lodash?

推荐答案

我将在输入上使用Object.entries,映射到嵌套对象,然后调用Object.fromEntries再次将其转换回去:

I'd use Object.entries on the input, map to a nested object, then call Object.fromEntries to transform it back again:

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的东西:

Object.fromEntries is a pretty new method, so for older browsers, either include a polyfill or use something like .reduce instead:

const input = { name: 'Bill', lastname: 'Smith'};
const newObj = Object.entries(input).reduce(
  (a, [key, value]) => {
    a[key] = { value };
    return a;
  },
  {}
);
console.log(newObj);

这篇关于如何用花括号包装json的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆