Home > database >  How to create a JS Array containing an JS Object as Key value pairs from string?
How to create a JS Array containing an JS Object as Key value pairs from string?

Time:10-09

I Have a javascript code

var jsString1 = [];
var jsString = [];
var val1, val2;
val1 = "test1";
val2 = "test2";
jsString1.push("key1");
jsString1.push(val1);
jsString1.push("key2");
jsString1.push(val2);
jsString.push(jsString1);
alert(JSON.stringify(jsString));

this will give the result as these

// current output
 [["key1","test1","key2","test2"]]

but I need to make one like these

// needed output
 [{"key1":"test1","key2":"test2"}]

How can I do it ? Please help me and thanks in advance.

CodePudding user response:

Normal you would only do

jsString1.push({
"key1":val1
"key2":val2
})

The code above only pushes into the array. You need it into the object then into the array.

CodePudding user response:

You have an array of arrays of keys and values [[key, value, key, value]]. If the array was in the form of [[key, value], [key, value], ...] (entries) we could use Object.fromEntries() to convert it to an object.

To transform the original an array of entries, map the array, use Array.from() to convert sub-arrays to tuples of [key, value], and then use Array.flat() to convert the 3d array to a 2d array of entries:

const toEntries = arr =>
  arr.map(subArr => 
    Array.from({ length: subArr.length / 2 }, (_, i) => 
      subArr.slice(i * 2, i * 2   2)
    )
  ).flat(1)

const arr = [["key1","test1","key2","test2"]];

const obj = Object.fromEntries(toEntries(arr))

console.log(JSON.stringify(obj));

  • Related