-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);

3
  • PS:: properties is the name of object Commented Feb 1, 2023 at 12:59
  • please add the wanted result. Commented Feb 1, 2023 at 13:03
  • Perhaps you meant x.push(properties[i]); Commented Feb 1, 2023 at 13:05

4 Answers 4

2
let x = Object.values(properties)
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

0

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

const items = Object.values();

5 Comments

values returns already an array, not an iterator.
@NinaScholz right, I keep forgetting which ones return an array. What were the examples returning an iterator?
for example Array#keys.
@NinaScholz oh yeah, so [1, 2, 3].keys() returns an array, but Object.keys([1, 2, 3]) returns an iterator. What a mess, I wonder if the only explanation of this is legacy.
vice versa ....
-1

Try this:

for (let property in properties) {
    propertiesArray.push(properties[property]);
}

1 Comment

rather iterate the Object.keys() to avoid unexpected inherited properties. (might as well use Object.values() at that point)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.