1

I am new in angular js. I have one array object as

var data = [{ id:1, name: 'Adam', email: '[email protected]', age: 12},
            { id:2, name: 'Amalie', email: '[email protected]', age: 12}];

Now, I want data as

var data_id = [{1},{2}];

So what should I have to get only id list from array object?

0

2 Answers 2

1

In Javascript, Objects are having key and value both.

var obj = {
  myKey: value,
}

You can try JavaScript array.map() method. It will return the array with the elements you want to access.

var data = [{ id:1, name: 'Adam', email: '[email protected]', age: 12},
            { id:2, name: 'Amalie', email: '[email protected]', age: 12}];
            
var result = data.map(function(item) {
  return item.id;
});

console.log(result);

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

Comments

1

EDIT: Question has been updated.

The format you want the data in ([{1},{2}]) cannot be achieved. A javascript object has to have a key and a value. so, {1} is invalid. But on the other hand if it's just the ids you want ([1,2]), see the mapping below and instead of returning {id: item.id}, just return item.id.

var data = [{ id:1, name: 'Adam', email: '[email protected]', age: 12},
            { id:2, name: 'Amalie', email: '[email protected]', age: 12}];

// [{id: 1, {id: 2}}]
var data_id = data.map(function(item){
    return { id: item.id};
});

// [1, 2]
var data_id = data.map(function(item){
    return item.id;
});

If you're using ES6, you could simplify the code

var data_id = data.map(item => ({ id: item.id}));

You can use javascript map function to extract just the id.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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.