How can I wrap the value of json with curly braces?

谁说我不能喝 提交于 2019-12-24 20:56:51

问题


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

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

And I want the value wrapped with curly braces like this

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

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


回答1:


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 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);



回答2:


You can loop through the keys of the object using for...in and update it like this:

const input = { name: 'Bill', lastname: 'Smith'};

for (const key in input) {
  input[key] = { value: input[key] }
}

console.log(input)

If you don't want to mutate the input and want to create a new object, then create another object and update it:

const input = { name: 'Bill', lastname: 'Smith'},
      output = {}

for (const key in input) {
  output[key] = { value: input[key] }
}

console.log(output)



回答3:


You can use lodash's _.mapValues() to return a new object with transformed values:

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>


来源:https://stackoverflow.com/questions/56895963/how-can-i-wrap-the-value-of-json-with-curly-braces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!