0

I want to build an JSON with name and value like name:"john".

This is my code:

var allFields = [];
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length;i++){

        name = inputs[i].name;
        item = inputs[i].value;
        allFields.push({name: item});
}
var alleFelder = JSON.stringify(allFields);
alert(alleFelder);

My problem is that "name" gets hardcorded into the JSON.

So instead of...: name:"john", lastname:"brooks", birthdate:"1.1.1999"

...im getting: name:"john", name:"brooks", name:"1.1.1999"

ncaffrey
  • 5
  • 2

1 Answers1

-1

You can use this simple function to add new keys with values to your object

const myObj = {}


function addKeyVal(obj, k, v){
  obj[k] = v;
}

const keys = ["name", "bday"];
const values = ["Jhon", "1-1-2020"];



for(let i = 0; i < keys.length; i++)addKeyVal(myObj, keys[i], values[i])

console.log(myObj)
Ahmed Gaafer
  • 1,603
  • 9
  • 26