1

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?

2
  • Try changing arr[i] = {key: val}; to arr[i] = {[key]: val}; Commented Sep 17, 2017 at 5:49
  • 1
    @Hasan - Thanks a lot. It works. Commented Sep 17, 2017 at 7:57

5 Answers 5

1

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] }))
);
Sign up to request clarification or add additional context in comments.

2 Comments

If you are going to discuss this new syntax, why not give its name, and even a reference?
Yeah, it's quite verbose. [key] is the key here though. Thanks a lot.
0

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?

Comments

0

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;
  
}

Comments

0

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"}}]

Comments

0

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);;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.