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?
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);
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;
}
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
}
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)
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))
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.