I am trying to get only 2 properties from array objects.
This is my array:
[
0: {_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)}
1: {_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}
]
I am trying to get only label and slug my expectation is :
[
0: {label: 'new 22', slug: 'new-22'}
1: {label: 'new 33', slug: 'new-33'}
]
I have tried like this way: but it's returning full array objects
let tempArray;
for (let i = 0; i < data.length; i += 2) {
tempArray = data.slice(data[i], data[i + 2]);
}
setAttributeLabel(tempArray);
You can use Array.prototype.map to filter out the required properties.
const array = [{_id: '621723ddc1f73de5f7e4dcb9', label: 'new 22', slug: 'new-22', vendor: 'admin', options: Array(1)}, {_id: '6217272ec1f73de5f7e4dcba', label: 'new 33', slug: 'new-33', vendor: 'admin', options: Array(1)}];
const newArray = array.map(({label, slug}) => ({label, slug}));
console.log(newArray);
Just iterate of the array and create a new object of required properties and push in temp array
const data = [{
_id: '621723ddc1f73de5f7e4dcb9',
label: 'new 22',
slug: 'new-22',
vendor: 'admin'
},
{
_id: '6217272ec1f73de5f7e4dcba',
label: 'new 33',
slug: 'new-33',
vendor: 'admin'
}
]
let tempArray = [];
for (let i = 0; i < data.length; i++) {
tempArray.push({
label: data[i].label,
slug: data[i].slug
})
}
console.log(tempArray);
You can user Array.map to create a new array. For each element mapped, you create a new object containing only the properties you need:
arr.map(a => { return { label: a.label, slug: a.slug } } );