如何用卷曲牙套将JSON的价值包裹起来



让我有这样的json(使用json.stringify(

{name:'bill',lastname:'smith'}

,我想要用像这样的卷曲括号包裹的值

{name:{value:'bill'},lastName:{value:'smith'}}

因此,使用JavaScript或Lodash这样做的任何想法?

我会在输入上使用 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);

您可以使用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)

您可以使用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>

最新更新