Stephen Ross
Stephen Ross

Reputation: 419

Convert Javascript Array to JSON User Defined Key/Value Pair

I need to take a string from a text input and convert it from an array to a JSON object.

let orderInputArray = ["key1", "value1", "key2", "value2"];
let json = {}
let key,value;

orderInputArray.forEach(function(keyValue) {
  json[key] = keyValue.value;
});

let orderInputJSON = JSON.stringify(orderInputArray);

I need it to look like:

[{"key1": "value1"}, {"key2": "value2"}]

I'm not quite sure how to do this with the for each loop. Can anyone shed some light?

Upvotes: 0

Views: 6680

Answers (7)

Mohammed Ashfaq
Mohammed Ashfaq

Reputation: 3426

let orderInputArray = ["key1", "value1", "key2", "value2"];
jsonArray = [];
orderInputArray.forEach((item, i, a)=> {if(i%2 === 0) jsonArray.push({item:a[i+1]})});

console.log(jsonArray)

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 191986

This is not the ideal way to create an object, but you can skip the key, create an object with the key/value using the current index (i), and push it to the result (orderInputObjects):

const orderInputArray = ["key1", "value1", "key2", "value2"];
const orderInputObjects = [];

orderInputArray.forEach(function(v, i, a) {
  if(i % 2) orderInputObjects.push({ [a[i - 1]]: v });
});

console.log(orderInputObjects);

Upvotes: 3

enno.void
enno.void

Reputation: 6579

Here my solution with splice:

var fruits = ["Banana", "Orange", "Apple", "Mango"];

var json = {};
while(fruits.length > 0){
    let a = fruits.splice(0,2)
    console.log(a)
    json[a[0]] = a[1]
}

console.log(json)

Upvotes: 1

bugwheels94
bugwheels94

Reputation: 31920

You can do this with reduce as well

let orderInputArray = ["key1", "value1", "key2", "value2"];
var l = orderInputArray.length;
var jsobj = orderInputArray.reduce(function(acc, v, i) {
    var o = {};
    if (i % 2 === 0 && i < l - 1) {
        o[v] = orderInputArray[i + 1];
        acc.push(o)
    }
    return acc;
}, []);
console.log(JSON.stringify(jsobj))

Upvotes: 1

brk
brk

Reputation: 50291

You can use filter to create an array of odd and even , then use reduce function to create the array of object

let orderInputArray = ["key1", "value1", "key2", "value2"];
let vals = orderInputArray.filter(function(item, index) {
  return index % 2 === 1

});
let keys = orderInputArray.filter(function(item, index) {
  return index % 2 === 0

}).reduce(function(acc, curr, index) {
  acc.push({
    [curr]: vals[index]
  })
  return acc
}, []);
console.log(keys)

Upvotes: 1

Aragorn
Aragorn

Reputation: 5289

forEach uses a call back function, therefore it is not guaranteed to finish before the let orderInputJSON = JSON.stringify(orderInputArray); in your code.

Try using

var i;

for (i =0; i < orderInputArray.length; i=i+2){
//create object here using orderInputArray[i] as key and orderInputArray[i+1] as value
}

Upvotes: 1

Siyavash
Siyavash

Reputation: 980

You can use a simple for loop and increment by 2 instead of 1

function arrayToKeyValue(array) {
  let updated = [];
  for (let i = 0; i < array.length; i += 2) {
    const key = array[i];
    const value = array[i + 1];
    updated.push({ key: value });
  }
  return updated;
}

Upvotes: 2

Related Questions