-1

I have an object like this in my NodeJS backend:

{
    "x": "2021",
    "y": {
        "Kumada, K": 2,
        "Wu, XY": 4,
        "da Silva, BJP": 2
    }
}

And i would need it to become like this:

{
    "x": "2021",
    "Kumada, K": 2
    "Wu, XY": 4,
    "da Silva, BJP": 2    
}

EDIT: The "y" is dynamic which means it can have any number of different names, for example:

{
    "x": "2021",
    "y": {
        "Josh, K": 2,
        "Bob": 4,
        "Joseph": 2,
        "John": 0
    }
}

Any tips? Appreciate any help!

jay2p
  • 75
  • 6
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Jun 19 '21 at 20:34
  • Do you know what keys it will have always? What is the structure of your incoming object. – Tushar Shahi Jun 19 '21 at 20:36
  • 1
    @TusharShahi they keys inside the Y object will be dynamic, can have multiple different properties in there. I'll update the question for better undestanding, sorry about that. – jay2p Jun 19 '21 at 20:39

2 Answers2

0

Below approach first creates an object based on a.y and then add all properties from a one by one using Object.keys(). Then it removes the y key, since it is not required.

let a = {
   "w" : "Hello",
    "x": "2021",
    "y": {
        "Kumada, K": 2,
        "Wu, XY": 4,
        "da Silva, BJP": 2
    }
}

let b = a.y;
Object.keys(a).forEach((x)=>{
  b[x] = a[x];
})
delete b.y

This will be a shallow copy

For eg : If you have a["x"] as { 'prop1' : 22, 'prop2' : 33 }. And you modify a["x"]["prop1"] = 22; This will be reflected in your final object too.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • Thank you very much! This is exactly what i needed, didnt know about Object.keys thats the part it was missing. I'm really sorry if my question was really noob or bad as people are downvoting it :(. – jay2p Jun 19 '21 at 20:51
  • Tip : always show whatever you have tried. No matter how small or wrong. – Tushar Shahi Jun 19 '21 at 20:52
0

Get to know spread syntax. It's magic sauce for this kind of thing

let o = {
    "x": "2021", "y": { "Kumada, K": 2, "Wu, XY": 4, "da Silva, BJP": 2 }
    }
let newobj = { ...o, ...o.y };
delete newobj.y;
console.log(newobj)
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • Thats a great solution aswell, no need for a forEach loop in it! Thank you very much for your help aswel! – jay2p Jun 19 '21 at 20:58