Home > Net >  How do I set value of nested object to key of current object?
How do I set value of nested object to key of current object?

Time:05-04

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"
  }
]

CodePudding user response:

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

CodePudding user response:

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.

  • Related