skip to Main Content

I just have a question if it is possible to destructure an object using an array of variables. I know it is possible if you know the name of the Object Keys but if you do not know the keys of the object (e.g. from an API) can this be done? Any suggestions would be great. Thank you.

const names = {
a: 'peter',
b: 'jane',
c: 'sam',
};

let vals = Object.keys(names);
console.log(vals);
// const { a, b, c } = names;
[vals] = names;
console.log(a, b, c);

2

Answers


  1. Method 1:

    const names = {
      a: 'peter',
      b: 'jane',
      c: 'sam',
    };
    
    var vals = [];
    for (var key in names) { // iterate through each key value pair
      vals.push(names[key]); // add value to array
    }
    
    console.log(vals);

    Method 2:

    const names = {
          a: 'peter',
          b: 'jane',
          c: 'sam',
        };
    
    var vals = Object.values(names);
    console.log(vals);
    Login or Signup to reply.
  2. If you want to get a value of list, there is a two way.

    let nameValueList = []
    for (const [key, value] of Object.entries(names)) {
       nameValueList.push(value)
    }
    console.log(nameValueList); // ["peter", "jane", "sam"]
    

    or

    console.log(Object.values(names)) // ["peter", "jane", "sam"]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search