0

I am a new to JSON and facing problems creating a very simple array.

I have the key,value pair received from an HTML form:

frm1 = {"fname":"John","lname":"Doe","location":"CA"};
frm2 = {"fname":"Jenny","lname":"Doe","location":"CA"};

I want to create a JSON like below:

{
  "employee":[
    {"fname":"John","lname":"Doe","location":"CA"},
    {"fname":"Jenny","lname":"Doe","location":"CA"}
]}

Trying to push the first form data(frm1) only by below code is not working.

var form1 = {"employee":[]};

form1.employee = frm1;

console.log(JSON.stringify(form1)); // prints form1 :{"employee" : ["fname","lname","location"]}

Only keys are printed. Please suggest.

3
  • Just to clarify: What you're working with are pure Javascript objects and arrays, not JSON. JSON is a textual format used to exchange data objects. Commented May 19, 2016 at 11:14
  • do i have to parse it then? Commented May 19, 2016 at 11:19
  • 1
    Well, that depends on if you're working with objects (as in the example) or strings (which may contain JSON). console.log(typeof frm1) will say either object or string. E.g. console.log(typeof '{"fname": "john"}') will say it's a string which needs to be parsed whereas console.log(typeof {"fname": "john"}) will say that it's a good ol' object. Commented May 19, 2016 at 11:22

3 Answers 3

2

Just apply them

var form1 = { employee: [frm1, frm2] };
Sign up to request clarification or add additional context in comments.

Comments

2

Either create the object with array elements

var frm1 = {
    "fname": "John",
    "lname": "Doe",
    "location": "CA"
  },
  frm2 = {
    "fname": "Jenny",
    "lname": "Doe",
    "location": "CA"
  };

var form1 = {
  "employee": [frm1, frm2]
};
console.log(JSON.stringify(form1));

or push elements later using push()

var frm1 = {
    "fname": "John",
    "lname": "Doe",
    "location": "CA"
  },
  frm2 = {
    "fname": "Jenny",
    "lname": "Doe",
    "location": "CA"
  };
var form1 = {
  "employee": []
};
form1.employee.push(frm1,frm2);

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

1 Comment

push accepts multiple arguments: form1.employee.push(frm1, frm2)
0

    var frm1 = {"fname":"John","lname":"Doe","location":"CA"}; 
    var frm2 = {"fname":"John","lname":"Doe","location":"CA"}; 
    var form1 = {"employee":[" ",""]};
  

    form1["employee"][0] = frm1;
    form1["employee"][1] = frm2;
    
  
     console.log(form1["employee"][0]);
    console.log(form1);
    console.log(JSON.stringify(form1));

Since the keys value is an array you can use push or use its array index

Sorry I misunderstood the question you want an array with multiple values for single object for employee

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.