Elias Khazzaka
Elias Khazzaka

Reputation: 117

json adding new element and updating old element using js

i have user input field with different variables, this means that the user can enter a lot of different values. and I want to save those values under the id of the object assigned to them. When adding them in a json variable, only one instance of the objects is added, any later insertion results in an update in the current variable.

 var items = {id: `${ID}`, name: `${name}`}

i want the json variable to be saved as an array in a file like this

 var items = [
              {id: `${ID}`, name:`${name}`},
              {id: `${ID}`, name:`${name}`}
             ]

also I don't want an item to be added if there is already one with the same id instead it would better when it updated

Upvotes: 0

Views: 63

Answers (2)

Sven.hig
Sven.hig

Reputation: 4519

You probably want something like this

let id=document.getElementById("id")
let Name=document.getElementById("name")
let insert=document.getElementById("insert")


data=[]

insert.addEventListener("click",()=>{
     ID=id.value
     name=Name.value
      console.log("clicked")

   
var items = {id: `${ID}`, name:`${name}`}
    // data.forEach(ele => {
     if(!data.some(x=>x.id==ID)) data.push(items) 
     else{
     data.forEach(ele =>{
       if(ele.id==ID) data.splice(data.indexOf(ele),1),data.push(items)
     })

     }
   
console.log(data)

})
<body>
  <div id="banner-message">
    <p>Hello World</p>
    <input id="id">
      <input id="name">
    <button id="insert">Change color</button>
  
  </div>
  
</body>

Upvotes: 0

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

Here you go , this is generic solution.

function AddToItems() {

  var length = (document.getElementsByTagName("INPUT").length);
  var elements = document.getElementsByTagName("INPUT");
  var items = [];
  for (let i = 0; i < length; i++) {
    items.push({
      id: elements[i].id,
      name: elements[i].value
    });
  }
  console.log(items);
}
Input1: <input type="text" id="input_1"/>
Input2: <input type="text" id="input_2"/>
Input3: <input type="text" id="input_3"/>
<button type="submit" onclick="AddToItems()">
Submit
</button>

Upvotes: 2

Related Questions