Home > Net >  How to Convert Nested Object in Key Value Pair in Javascript
How to Convert Nested Object in Key Value Pair in Javascript

Time:07-02

I want to do this with programming

Problem

  attributes: {
    allow: [ '0' ],
    create: [ '0' ],
    all: [ '0' ],
    rfid: [ '0' ],
}

What I want is

  attributes: {
    allow:'0',
    create: '0',
    all:'0',
    rfid: '0',
}

CodePudding user response:

Functional approach:

You can use Object.entries to turn an object { a: 1, b: 2 } into an array of arrays (containing pairs of keys and values) [['a', 1], ['b', 2]]. You can then use Array#map to apply an operation on each and mapping each element of the array to the return value of the operation. In our case, we'll actually have something like [['allow', ['0']], ...] at that point and want to map it to [['allow', '0'], ...]. Then at the end, we undo the first operation using Object.fromEntries to get an object back.

The mapping operation can be simply ([k, [v]]) => [k, v]. Using destructuring, we get an expressive way of extracting the value that we need and returning it.

Now since the whole thing seems to be inside another object with attributes as key (and I don't know if there can be other keys), we'll return another such object with attributes replaced and the other keys preserved:

function transform (object) {
  return {
    ...object,
    attributes: Object.fromEntries(
      Object.entries(object.attributes).map(([k, [v]]) => [k, v])
    )
  }
}

Imperative approach:

This approach is simpler, but will mutate your object. You can loop over the keys in the attributes object and replace each value with its own first array element, as follows:

function transform (object) {
  for (const key in object.attributes) {
    object.attributes[key] = object.attributes[key][0]
  }
  
  return object
}
  • Related