0

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?

8
  • 2
    Why dont you use a for loop with an increment of 2 per iteration? Commented Oct 8, 2018 at 16:57
  • look for array.splice Commented Oct 8, 2018 at 16:57
  • Any reason you must specifically use a forEach loop vs a regular for loop? Commented Oct 8, 2018 at 16:57
  • @mr.void How can splice help in this case? Commented Oct 8, 2018 at 16:58
  • @WookieCoder i think its more handy than a old-style for-loop Commented Oct 8, 2018 at 16:58

7 Answers 7

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, the issue was on my side. This works perfectly.
Quick question: if I wanted to use {"key1" : "value1","key2" : "value2","key3" : "value3"} instead, how would I modify the code? I also noticed " " surrounding the array brackets, how would I remove those?
This should give you an object - if(i % 2) obj[a[i - 1]] = v;. I'm not sure what you mean about the brackets.
I actually stringified the object later on in my code, so that was the issue. Thanks for all your help!
2

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

Comments

1

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
}

Comments

1

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)

Comments

1

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

Comments

1

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)

Comments

1

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)

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.