3

I am fairly new to Vue and JS but I am making API calls and getting a JSON response then sending the response to an empty array. How do I get the ID of each object in the array?

The array that the response is being pushed to is structured like this

groups: [
  {
    "id": "0",
    "name": "a",
    "price": 5
  },
  {
    "id": "1",
    "name": "b",
    "price": 5
  },
  { 
    "id": "2",
    "name": "c",
    "price": 5
  }
]

I'd like to pull the Id of each object and push the values to an empty array

for(var group in this.groups) {
  if (this.groups.hasOwnProperty(0)) {
    this.group = this.groups[0];
    this.groupsId.push(this.innerObj);
  }
}

The error I'm getting is saying Cannot read property '0' of undefined at eval
Ideally I'd like an array that has all the Ids of each object.

3 Answers 3

2

this.groups.hasOwnProperty(0) should be group.hasOwnProperty('id')

Use Array.prototype.map() to iterate over an array of objects and collect every ID into a new array:

const res = {
  groups: [{
      "id": "0",
      "name": "a",
      "price": 5
    },
    {
      "id": "1",
      "name": "b",
      "price": 5
    },
    {
      "id": "2",
      "name": "c",
      "price": 5
    }
  ]
};

const ids = res.groups.map(obj => {    // you use this.groups
  if(obj.hasOwnProperty('id')) return  obj.id;
});

console.log(ids)

Sign up to request clarification or add additional context in comments.

4 Comments

Should it be group.hasOwnProperty('id')?
I'm talking about your first sentence, where you were trying to correct the existing code. groups is an array. It doesn't have a property named id.
@Rainbolt uhh thanks I thought you were referring to the example code
@justarookie you're welcome. And thanks to Rainbolt for the eagle-eye.
0

There is the Array.map() method:

this.groupsId = this.groups.map(i => i.id);

If you already have elements in this.groupsId you can append the ids using Array.concat():

this.groupsId = this.groupsId.concat(this.groups.map(i => i.id));

Comments

0

You can use Array.prototype.reduce to loop and check if there's id.

const groups = [
  {"name": "a","price": 5},
  {"id": "1","name": "b","price": 5},
  { "id": "2","name": "c","price": 5}
];
const list = groups.reduce((groupIds, group) => group.id ? [...groupIds, group.id] : groupIds, []);
console.log(list);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.