Skip to content Skip to sidebar Skip to footer

How Can I Wrap The Value Of Json With Curly Braces?

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' }, lastnam

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

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

Solution 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);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Post a Comment for "How Can I Wrap The Value Of Json With Curly Braces?"