0

I have a JSON object with this structure:

{"Firstname":"john","Lastname":"doe"}

How do it change it to an array with this structure with the name 'abc'(?):

users: [{"Firstname":"john","Lastname":"doe"}]

This is I'm building my object from input values:

var obj = {};
obj.Firstname = document.getElementById("firstName").value;
obj.Lastname = document.getElementById("surname").value;
 console.log(obj);
var jsonStringObj = JSON.stringify(obj);
 console.log(jsonStringObj );

which returns:

{"Firstname":"john","Lastname":"doe"}

thanks!

1
  • 1
    i do not understand, what you are trying to achieve and what fails... Commented Jul 21, 2020 at 10:57

2 Answers 2

1

You need to create new array and push the entire object.

var x = {"Firstname":"john","Lastname":"doe"};
var newArray = [];
newArray.push(x);

console.log([{"Firstname":"john","Lastname":"doe"}])

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

5 Comments

Thank you!!! how do I add a name property to e.i users: [{"Firstname":"john","Lastname":"doe"}] thanks!!
what is your desire output ? can you update that in your question
the output should be > users: [{"Firstname":"john","Lastname":"doe"}]
try this @fosowe var newobj={"users":newArray}; console.log(newobj);
You do not need to push x into the array, you can create the array with x in it, like var newArray = [x];
0

You can create an object, having a key of user and a value of an array, having your item:

var jsonStringObj = {user: [JSON.stringify(obj)]};

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.