Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
How to Convert Nested Object in Key Value Pair in Javascript

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',
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!