Reputation: 67
I am trying to return an array of key-value pairs: [{"a": 1},{"b": 2},{"c": 3}]
from a given array of keys: ["a", "b", "c"]
and an array of values: [1, 2, 3]
I have tried this:
let arr = [], obj = {}, key, val;
const keyValuePairs = (k, v) => {
if (k.length === v.length) {
for (var i = 0; i < k.length; i++) {
key = k[i]; val = v[i];
arr[i] = {key: val};
}
} return arr;
};
keyValuePairs(["a", "b", "c"], [1, 2, 3]);
But it's returning - [ { key: 1 }, { key: 2 }, { key: 3 } ]
How can I do it?
Upvotes: 1
Views: 135
Reputation: 10262
you can use reduce method also as per your requirement.
see below example..
let keys = ["a", "b", "c"],
values = [1, 2, 3],
result = keys.reduce((r,v,i)=>r.concat({[v]:values[i]}),[]);
console.log(result);;
Upvotes: 0
Reputation: 313
using lodash you can do this in one line with _.map
or the vanilla Array.prototype.map
and using the index i
to stripe across the arrays.
var keys = 'abc'.split('');
var values = '123'.split('');
var result = _.map(keys, (key, i) => ( { [keys[i]] : values[i] } ) );
console.log(JSON.stringify(result));
yields:
[{"a":"1"},{"b":"2"},{"c":"3"}]
you can also continue this pattern dimensionally:
var keys = 'abc'.split('');
var values = '123'.split('');
var valuesValues = 'xyz'.split('');
var result = _.map(keys, (key, i) => ( { [keys[i]] : { [ values[i] ]: valuesValues[i] } } ) );
console.log(JSON.stringify(result));
yields:
[{"a":{"1":"x"}},{"b":{"2":"y"}},{"c":{"3":"z"}}]
Upvotes: 0
Reputation: 18923
Try this(simple solution):
var answer = keyValuePairs(["a", "b", "c"], [1, 2, 3]);
console.log(answer);
function keyValuePairs(arrOne, arrTwo){
var returnArr = [];
for(var i = 0; i < arrOne.length; i++){
var obj = {};
obj[arrOne[i]] = arrTwo[i];
returnArr[i] = obj;
}
return returnArr;
}
Upvotes: 0
Reputation: 18268
If you're targeting a new enough browser, or are using babel, there is a new syntax that allows this easily:
arr[i] = {[key]: val};
Otherwise you will need to use multiple lines to set the key
let arr = [], obj = {}, key, val;
const keyValuePairs = (k, v) => {
if (k.length === v.length) {
for (var i = 0; i < k.length; i++) {
key = k[i]; val = v[i];
var newObj = {};
newObj[key] = val;
arr[i] = newObj;
}
} return arr;
};
Just general code comments: You have a bunch of variables out of the scope of the function. It's also quite verbose. You can write the entire function like this:
const keyValuePairs = (k, v) => (
k.map((key, index) => ({ [key]: v[index] }))
);
Upvotes: 1
Reputation: 22876
a = ["a", "b", "c"], b = [1, 2, 3]
c = a.map((k, i) => ({[k]: b[i]}))
console.log(JSON.stringify(c))
How do I zip two arrays in JavaScript?
Upvotes: 0