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

140
Views
How do I set value of nested object to key of current object?

This array has the key to substitute with nested key of 'name'

const arr = ['status', 'user', ...]  <-- This array contains key to be replaced with name 

This is what my current response object is

[
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
     }
  }
]

How do I modify the above array of objects to this below

[
  {
    "id": 11,
    "location": "Mumbai",
    "status": "NEW",
    "user": "Rakesh"
  }
]

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

can try below code

const keys = ['status', 'user']
let arr = [
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
     }
  }
]

arr.map(a => keys.forEach(k => {
   if(a[k] && a[k].name) a[k] = a[k].name
}));

console.log(arr);

about 4 years ago · Juan Pablo Isaza Report

0

I'd try this one:

const results = [
  {
    "id": 11,
    "location": "Mumbai",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Rakesh"
    }
  }, {
    "id": 12,
    "location": "Helsinki",
    "status": {
      "name": "NEW"
    },
    "user": {
      "name": "Samuli"
    }
  }
];

const flattenObject = ([key, value]) => ((typeof value === 'object') ? {[key] : value[Object.keys(value)[0]]} : {[key]: value});

const reduceToSingleObject = (acc, b) => ({...acc, ...b});

const actualResults = results.map((result) => Object.entries(result).map(flattenObject).reduce(reduceToSingleObject));


console.log(actualResults);

Explanation:

  1. flattenObject is a function to flatten structure of object inside object. This only takes the first prop (without knowing the name of the key). If you, for some reason, would need to flatten several key-values, then it'd need whole different kind of helper function to sort that out.

  2. reduceToSingleObject is a function to put all the key-value pairs into a single object. This could have been done already in flattenObject function, but for the clarity, I separated it to a normal map - reduce pattern.

  3. actualResults is the outcome where we go through all the entries of your original results.

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!