Reputation: 6629
I have the following array
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
What i want is to get
const finalarr = [1,3]
That is get an array of values with key value
So i have tried
const finalarr = arr.map(obj=>obj.value)
The above returns [1, undefined, 3];
I have also tried
const finalarr = arr.map(obj => {
if (obj.value) {
return obj.value;
}
})
but i still get [1, undefined,3]
How can i adjust this to only return the values of objects with a key value to eliminate the undefined key?
Upvotes: 1
Views: 751
Reputation: 37755
You can use reduce
const array = [{name:'one;', value:1},{name:'two'},{name:'three', value:3}]
let final = array.reduce((op,{value})=>{
if(typeof value !== 'undefined'){
op.push(value)
}
return op
},[])
console.log(final)
map used to map complete array back with changed values it doesn't skip value you can use map and filter for you purpose
const arr = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const finalarr = arr.filter(({value})=>typeof value !== 'undefined').map(({value})=> value)
console.log(finalarr)
Upvotes: 1
Reputation: 33726
Use the function reduce
because the function map
returns an array with the same length of the source array.
const finalarr = arr.reduce((a, {value}) => {
if (value) a.push(value);
return a;
}, []);
Important: your approach is skipping the objects with values equal to zero 0
.
Example
const arr = [{name:'one', value:1},{name:'two'},{name:'three', value:3}];
const finalarr = arr.reduce((a, {value}) => {
if (value) a.push(value);
return a;
}, []);
console.log(finalarr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 7080
The Array .map
method will return another array with the exact same size of the original array.
If you want a result with different size, you cannot do it with pure .map
only.
What you can do is to first .filter
out objects without .value
property:
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const result = array
.filter(obj => typeof obj.value !== 'undefined')
.map(obj => obj.value);
console.log(result);
Otherwise, you can also use .reduce
:
const array = [{name:'one', value:1},{name:'two'},{name:'three', value:3}]
const result = array.reduce((arr, obj) => {
if (typeof obj.value !== 'undefined')
arr.push(obj.value);
return arr;
}, []);
console.log(result);
Upvotes: 1