'How can I take only few property from my array objects in js
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);
Solution 1:[1]
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);
Solution 2:[2]
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 } } );
Solution 3:[3]
Instead of using loops, try to use javascript pre-defined functions like maps.
array.map(({ label, slug }) => {
return {label, slug}
});
Solution 4:[4]
You can use Array.prototype.reduce to loop through the data set and return only the value which you need as part of a new object
let data = [{_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 result = data.reduce((accumulator, current) => {
return accumulator.concat({label: current.label, slug: current.slug});
}, []);
console.log(result);
Solution 5:[5]
Use Array.map() to iterate the input array and get the required properties from an object.
// Input array
const arr = [
{_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)}];
// Array.map() to iterate the input array and get the required properties from an object.
const res = arr.map(({label, slug}) => {
return {label, slug}
});
// Result
console.log(res);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | brk |
| Solution 2 | Alexander van Oostenrijk |
| Solution 3 | Jijo Alexander |
| Solution 4 | Yves Kipondo |
| Solution 5 | Rohìt JÃndal |
