alia
alia

Reputation: 300

How to access and sort keys in nested objects in Javascript?

I have a nested object like this

info ={

"id-1": 
{
name: Jane, 
age: 35, 
experience: "7+",
position: manager, 
 
},

"id-2": 
{
age: 38, 
name: John, 
position: manager, 
experience: "9+", 
},

"id-3": 
{
age: 42, 
experience: "12+", 
position: manager, 
name: Max, 
}

and I have a string

let myString ="name, age,position, experience"

I need to access keys in objects (name, age, position, experience) and sort them according to this string, so keys in the object would be in the same order as in myString, like this:

"id-1": 
{
name: Jane, 
age: 35, 
position: manager, 
experience: "7+",
},

How can I access keys in the nested objects and sort them in order? When I try to use Object.keys(info) it returns id-1, id-2, id-3 not name, age, position, experience. Please help, I can't seem to figure out a way.

Upvotes: 1

Views: 190

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

First, most of the values of your keys are invalid. For example 7+ isn't a string, number or boolean and words like manager and John will be treated like variables if they don't have quotes around them. So your data needs to be fixed up.

Next, instead of wrapping the objects in an object that only has sequential key names (dashes are illegal syntax in key names unless the key names are quoted by the way), just place all the objects in an Array.

Then, just loop over the objects in the array and manually extract the individual key values you want in the order you want them. There is no need to think about re-sequencing the order that they are stored in.

let info = [ 
  {name: "Jane", age: "35", experience: "7+", position: "manager" },
  {age: "38", name: "John", position: "manager", experience: "9+"},
  {age: "42", experience: "12+", position: "manager", name: "Max"}
];

let keyNames = ["name", "age", "position", "experience"];

// Loop over the objects in the array
info.forEach(function(obj){
  let output = ""; // Will hold the output for one object at a time
  
  // Loop over the key names in the array so we go in the desired order
  keyNames.forEach(function(key){
    // Build up the string with they key name and the key value
    output += key + ": " + obj[key] + " ";
  });
  
  console.log(output); // Write out the string for the object
});

Upvotes: 1

Related Questions