-1

I am calling an API and got a response an an object in the following form. I would like to append the objects to an array in order to iterate them later.

Using push I got a list of strings == ['Account','AccountName','AccountServiceHomepage'] I would like to push the entire object to the array so for x[0] I get Account as an object not as a string.

Does anyone have a clue?

Snippet

let properties = {
  Account: {
    label: 'Account',
    key: 'Account',
    description: { en: '' },
    prefLabel: { en: 'test' },
    usageCount: '0'
  },
  AccountName: {
    label: 'AccountName',
    key: 'AccountName',
    description: { en: '' },
    prefLabel: { en: '' },
    usageCount: '0'
  },
  AccountServiceHomepage: {
    label: 'AccountServiceHomepage',
    key: 'AccountServiceHomepage',
    description: { en: '' },
    prefLabel: { en: '' },
    usageCount: '0'
  }
}  
  
x = [];
for (i in properties) {
  x.push(i);
};

console.log(x);
Yogi
  • 6,241
  • 3
  • 24
  • 30

4 Answers4

2
let x = Object.values(properties)
Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
1

let properties = {
  Account: {
    label: 'Account',
    key: 'Account',
    description: { en: '' },
    prefLabel: { en: 'test' },
    usageCount: '0'
  },
  AccountName: {
    label: 'AccountName',
    key: 'AccountName',
    description: { en: '' },
    prefLabel: { en: '' },
    usageCount: '0'
  },
  AccountServiceHomepage: {
    label: 'AccountServiceHomepage',
    key: 'AccountServiceHomepage',
    description: { en: '' },
    prefLabel: { en: '' },
    usageCount: '0'
  }
}

x = [];
for (i in properties) {
  x.push(properties[i]);
};

console.log(x);
HTS Pankaj
  • 11
  • 1
  • Up vote, but answers should also include a description of how the code works. For example, "Change the code to push the object rather than the key name using x.push(properties[i])" – Yogi Feb 01 '23 at 13:25
0

You can convert object to an array (ignoring keys) like this:

const items = Object.values();
Robo Robok
  • 21,132
  • 17
  • 68
  • 126
-1

Try this:

for (let property in properties) {
    propertiesArray.push(properties[property]);
}
CMartins
  • 3,247
  • 5
  • 38
  • 53
  • rather iterate the `Object.keys()` to avoid unexpected inherited properties. (might as well use `Object.values()` at that point) – pilchard Feb 01 '23 at 13:07