eugene
eugene

Reputation: 143

How do I extract items out of a dictionary

I have a dictionary which looks like this:

"Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
}

I need it to go into an array and end up like this:

"Player details": [
    {
        "player_id": "2",
        "color_one": "blue",
        "color_two": "red"
    },
    {
        "player_id": "4",
        "color_one": "white",
        "color_two": "black"
    }
]

I have tried the following, but the "value" still remains:

Object.entries(myDictionary).forEach(([key, value]) => {
   newArray.push({value})
});

I feel I am almost there, can anyone assist?

Upvotes: 1

Views: 75

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281686

You need to loop over myDictionary["Player Details"] and and push value into newArray instead of { value }

or you could do it in one line using Object.values

Object.values(myDictionary["Player Details"])

const myDictionary = {
  "Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
  }
}

const newArray = [];

Object.entries(myDictionary["Player Details"]).forEach(([key, value]) => {
   newArray.push(value)
});

console.log(newArray);

// Or a single one liner

console.log(Object.values(myDictionary["Player Details"]));

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115222

Just get values from the object using Object.values method which returns object property values in an array.

let data = {
  "Player Details": {
    "Sally Smith": {
      "player_id": 2,
      "color_one": "blue",
      "color_two": "red"
    },
    "John Smith": {
      "player_id": 4,
      "color_one": "white",
      "color_two": "black"
    }
  }
}


let res = {
  'Player Details': Object.values(data['Player Details'])
};

// or in case you justt need the array then 
let res1 = Object.values(data['Player Details']);

console.log(res)
console.log(res1)

FYI : Since there is whitespace in your property you can't use dot notation for accessing property instead of that use bracket notation.

Upvotes: 3

Code Maniac
Code Maniac

Reputation: 37755

You can simply use Object.values

let obj = {"Player Details": {
    "Sally Smith": {
        "player_id": 2,
        "color_one": "blue",
        "color_two": "red"
    },
    "John Smith": {
        "player_id": 4,
        "color_one": "white",
        "color_two": "black"
    }
}}
let op = {'Player Details' : Object.values(obj['Player Details'])}

console.log(op)

Upvotes: 1

Related Questions