How to populate multiple input fields from an array of objects

array of objects javascript
javascript array
get value from array javascript
push user input to array javascript
store input values in array jquery
jquery get input array value by index
jquery get value from array of objects
javascript foreach

What Am I trying to achieve: -less DOM calls in viewData function and overall a cleaner aproach to it.

My code and what I've done so far:

function viewData(){
var uid=document.getElementById("viewUserId").value;
for(i in users){
  if(users[i].id==uid){
   document.getElementById("nameEditInput").value=users[i].name;
   document.getElementById("userNameEditInput").value=users[i].username;
   document.getElementById("emailEditInput").value=users[i].email;
   document.getElementById("streetEditInput").value=users[i].address.street;
   document.getElementById("suiteEditInput").value=users[i].address.suite;
   document.getElementById("cityEditInput").value=users[i].address.city;
   document.getElementById("zipEditInput").value=users[i].address.zipcode;
   document.getElementById("latEditInput").value=users[i].address.geo.lat;
   document.getElementById("lngEditInput").value=users[i].address.geo.lng;
}
}

My idea :

I thought of giving my inputs a common class instead of an ID (for example "viewInfo") and create an array that stores my inputs. After that,I could parse through that array and assign my object values to my class input array.The problem I encountered with this was that I didn't know how to parse through my object.

var x = document.getElementsByClassName('viewInfo');
for(i in users){
 if(users[i].id==uid){
    for(k in x){
       x[k].value=users[k].[i]; //this gives me an error :Unexpected token [
}}}

You have to give to your inputs a name field, wich will be the equivalent attribute in user object

var inputs = document.getElementsByClassName('viewInfo');
const user = users.find(u => { return u.id === uid })
if (user) {
  Object.keys(inputs).forEach(i => {
    let inputName = inputs[i].getAttribute('name')
    inputs[i].value = user[inputName]
  })
}

For nested properties in user object, you can use an attribute name like this <input name="address.geo.lat" value="74023"> and then use the split and a recursive function to get the nested value of the object

const users = [
  {
    id: 1,
    name: 'Bob',
    username: 'bob01',
    email: 'bob@gmail.com',
    address: {
      street: 'Letsby Avenue',
      suite: '999',
      city: 'London',
      zipcode: 90210
    }
  },
  {
    id: 2,
    name: 'Bob2',
    username: 'bob02',
    email: 'bob2@gmail.com',
    address: {
      street: 'Letsby Avenue',
      suite: '999',
      city: 'London',
      zipcode: 90210
    }
  }
]

function getNestedValue(obj, keys) {
  let key = keys.shift()
  if (keys.length) {
    return getNestedValue(obj[key], keys)
  }
  return obj[key]
}

function viewData(){
  var uid=document.getElementById("viewUserId").value;
  var inputs = document.getElementsByClassName('viewInfo');
  const user = users.find(u => { return u.id === parseInt(uid) })
  if (user) {
    Object.keys(inputs).forEach(i => {
      let inputName = inputs[i].getAttribute('name');
      inputs[i].value = getNestedValue(user, inputName.split('.'))
    })
  }
}
viewData()
<html>
  <body>
    <form>
      <input type="hidden" id="viewUserId" value="2">
      <input class="viewInfo" name="name">
      <input class="viewInfo" name="username">
      <input class="viewInfo" name="email">
      <input class="viewInfo" name="address.street">
      <input class="viewInfo" name="address.suite">
      <input class="viewInfo" name="address.city">
      <input class="viewInfo" name="address.zipcode">
    </form>
  </body>
</html>

.serializeArray(), serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a  This also populates the array with objects, but they all refer to the same object. In the MDN web docs on the fill method it says: When fill gets passed an object, it will copy the reference and

First, I'd get the user lookup out of the loop. Then, document.querySelectorAll() will get all the elements of a class. Since the html element ids match the user properties, a little string manipulation on the id will let you set the value of the correct property in a single statement...

let users = [{
    id: 5,
    name: "Peter",
    email: "peter@gmail.com"
  },
  {
    id: 6,
    name: "Paul",
    email: "paul@yahoo.com"
  },
  {
    id: 7,
    name: "Mary",
    email: "mary@godaddy.com"
  }
];

function clicked() {
  let uid = parseInt(document.getElementById("userId").value);
  let user = users.find(u => u.id === uid);  // lookup the user
  if (!user) {
    alert(`No such uid ${uid}`);
    return;
  }

  document.querySelectorAll('.myClass').forEach(function(el) {
    let elementId = el.id;
    let propName = elementId.replace('EditInput', '');  // the id has a suffix
    el.value = user[propName];  // set the value from the user

  });
}
Enter a user id (5, 6 or 7 are valid) <input id="userId"></input>
<button onClick="clicked()">Go</button><br/><br/>
<input class="myClass" id="nameEditInput"></input>
<input class="myClass" id="emailEditInput"></input>

.map(), A function object that will be invoked for each element in the current set. If you wish to process a plain array or object, use  The form fields is an array of Field objects – but all we need to worry about is replacing the correct field’s choices property. Changing the choices What kind of data you want to replace choices with is entirely up to you, but a field’s choices property needs an array that has the elements ‘text’ and ‘value’.

You could achieve this with only 1 (or 2...) DOM calls if you're willing to create the input fields with scripting.

let uuid = document.getElementById('viewUserId').value
let user = users.find(user => user.id == uuid)

if (user) {
  let form = document.createElement('form')

  Object.keys(user).forEach(key => {
    let input = document.createElement('input')

    input.setAttribute(key, user[key])
    input.setAttribute('name', key)

    form.appendChild(input)
  })

  document.append(form)
}

How to make an array out of user inputs in JavaScript, (input fields or query strings?) or are you simply trying to grab the value out on an HTML element? as Jason Loveman How do I add multiple objects to a single array list in Javascript? 88,835 Views. I am trying to get the value from muliple inputs with the same id in an array. I already used the forum, but haven't find a solution for me. Exmaple <input type="hidden" value="'+image_url+'"

How about storing the values in an object. Each property key would would have an input in the HTML with a corresponding name. You can then iterate over the keys/values and add the value to the input with that key.

const obj = {
  name: 'Bob',
  username: 'bob01',
  email: 'bob@gmail.com',
  address: {
    street: 'Letsby Avenue',
    suite: '999',
    city: 'London',
    zipcode: 90210
  }
};

// Cache the inputs
const inputs = Array.from(document.querySelectorAll('input'));

function addProps(inputs, obj) {

  // Loop over the object entries (k = key, v = value)
  for (let [k, v] of Object.entries(obj)) {

    // If the current property is another object
    // (in this case `address`) call the function again
    // with that object
    if (typeof obj[k] === 'object') {
      addProps(inputs, obj[k]);
    } else {

      // Find the input where the name matches the key
      // and set its value
      inputs.find(input => {
        return input.getAttribute('name') === k;
      }).value = v;
    }
    
  }
}

// Call the function passing in the inputs and data object
addProps(inputs, obj);
<input name="name" />
<input name="username" />
<input name="email" />
<input name="street" />
<input name="suite" />
<input name="city" />
<input name="zipcode" />

JavaScript Array Reference, Array Object. The Array object is used to store multiple values in a single variable​: var cars = ["Saab", "Volvo", "BMW"];. When I checked the Angular Material autocomplete component, it looked like it was designed for a single input field. There wasn’t even a single reference implementation for multiple input fields

JavaScript array: Add items in a blank array and display the items , xad • 8 months ago. (function() { const input = document.querySelector(".input  Java: populate an array of objects, each with multiple parameters, from a file? Well I'm in a pickle. I'm trying to make a program here that can read from a text file, populate a number of objects (one per line of the file), and assign data from the file to variables within the objects (a little bit of everything here, not just one type of

Reactjs, Howdy, Campers. I have a react app with two child components, one that has a single static input field  Summary: Learn about creating an array of arrays in Windows PowerShell, and see how to store numerical data and rich objects in elements. Microsoft Scripting Guy, Ed Wilson, is here. Yesterday in Charlotte, North Carolina in the United States, it was 60 degrees Fahrenheit (that is 15 degrees Celsius according to my unit conversion module).

How to get all selected checkboxes in an array using jQuery , If there are multiple event values, separate them by space. Event must be a valid. childSel: This parameter is optional. It  hi, i'm having problem on how to auto-populate the drop down list (Wall Assignment) based on the Text box fields (Name). I am using Adobe Acrobat Pro Dc. The table with Name column is from page 2, while the Wall Assignment drop down, is on page 3. Whenever the user enters a Name, it will auto-popula

Comments
  • jsfiddle.net/afnb691k Didn't know how to format my code in comment so I just pasted it in jsfiddle. I didnt implement the whole split search ,but it should work for non-nested properties ,right?
  • @jsbeginner97 I put a snippet with the exemple in my answer
  • Just out of curiosity : how would you do the reverse of this thing? populating an object from array with values from input?
  • jsfiddle.net/o461qnds/6 I managed to come up this, but I couldnt avoid creating a new object.Any idea of how I could modify the initial users array instead?
  • @jsbeginner97 I added a fiddle on the answer
  • I think this way is even slower than the first solution he used. Because you call the document.querySelector multiple time, just as he do with his document.getElementById, but the querySelector function has a longer execution than the getElementById
  • If these aren't the only inputs on my page ,could i try to use const inputs = Array.from(document.getElementByClassName('viewInfo')); instead ?
  • Oh nevermind,I can use querySelector with a class name as well
  • If you're targeting more than one element you need querySelectorAll.