Home > Enterprise >  How do i assign key / value pairs of an array of strings
How do i assign key / value pairs of an array of strings

Time:07-06

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']

I'd like to assign key value pairs of the strings i have in the array above

for example:

[{drink: 'soda'},
 {name: 'john'},
 {someKey:'someValue'}
]

I've spent hours trying to figure this out... I've tried approaching it with the map method but my limited knowledge on javascript is consistently returning errors...

I'd really appreciate it if someone could help me out. Thanks

CodePudding user response:

You can do it with a simple for loop:

let arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'];

let result = [];

for(let i = 0; i < arr.length; i =2) {
  let obj = {}
  obj[arr[i]] = arr[i 1];
  result.push(obj)
}
console.log(result)

CodePudding user response:

A simple old-school loop increasing the step by 2 on each iteration.

Note: this will give you a single object with key/value pairs which makes (to my mind) a more useful data structure than an array of objects with one key/value pair each. If you're looking for an array of objects @sonEtLumiere's answer is the right one.

const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue'];

// Initialise empty object
const out = {};

// Loop over the array in steps of 2 so
// that we can access `i` (the key) and 
// `i   1` (the value) on each iteration
for (let i = 0; i < arr.length; i  = 2) {
  out[arr[i]] = arr[i   1];
}

console.log(out);
console.log(out.drink);
console.log(out.name);
console.log(out.someKey);

CodePudding user response:

That would be the easiest way:

const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']

const obj = {}
for (let i = 0; i < arr.length; i  = 2) {
  obj[arr[i]] = arr[i   1]
}

console.log(obj)

Or if you really want a oneliner

const arr = ['drink', 'soda', 'name', 'john', 'someKey', 'someValue']
const result = arr.reduce((fin, str, i, arr) => i & 1 ? fin : { ...fin, [str]: arr[i   1] }, {})
console.log(result)

  • Related