I have two array, one is type of String and second one is number. How can I combine these conditionally as key value objects.
For example:
var fruits = [
"Apple",
"Banana" ,
"Apricot",
"Bilberry"
]
var count = [3,5,0,2]
I want to combine fruits
and count
array as key value object and which count is not 0
Expected:
var merge = [{"Apple":3},{"Banana" :5},{"Bilberry":2}]
What i have tried is:
var merge = _.zipObject(["Apple","Banana" ,"Apricot","Bilberry"], [3,5,0,2])
and result is:
{"Apple":3,"Banana":5 ,"Apricot":0,"Bilberry":2}
Try this vanilla js solution as well using filter
, Object.values
and map
var output = count.map((s, i) => ({
[fruits[i]]: s
})).filter(s => Object.values(s)[0]);
Demo
var fruits = [
"Apple",
"Banana",
"Apricot",
"Bilberry"
];
var count = [3, 5, 0, 2];
var output = count.map((s, i) => ({
[fruits[i]]: s
})).filter(s => Object.values(s)[0]);
console.log(output);