0

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.

2 Answers 2

1

Normally, you would only do

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

Your code only pushes into the array.

You need to create an object first, and then add the object into the array.

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

1 Comment

its not pushing values in the above format
1

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

3 Comments

How to add the 3rd key and its value ?
Push them to jsString1 array.
@Gopipuli any reason you can't just create an object an push it into an array? It seems like you're over-complicating things.

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.