1

I have inputs like this:

<input type="text" id="contact[actif]" name="contact[actif]">
<input type="text" id="contact[sql]" name="contact[sql]">
<input type="text" id="interlocuteur[actif]" name="interlocuteur[actif]">
<input type="text" id="interlocuteur[sql]f" name="interlocuteur[sql]">

I have an object like this which comes from JSON stored in sessionStorage:

contact: {
  actif: true,
  sql: "SELECT * from w "
},
interlocuteur:{
  actif: true,
  sql: "select * from l"
}

How I can fill my inputs with values from the object?

2 Answers 2

2

Assuming the point of the question is that you don't know the names of the object keys at runtime you could could use two loops through the keys of the object deserialised from the JSON. Then you can use the keys you retrieve to build the selector string for the elements, something like this:

var data = {
  contact: {
    actif: true,
    sql: "SELECT * from w "
  },
  interlocuteur: {
    actif: true,
    sql: "select * from l"
  }
}

Object.keys(data).forEach(function(outerKey) {
  Object.keys(data[outerKey]).forEach(function(innerKey) {
    var selector = `#${outerKey}\\[${innerKey}\\]`;
    $(selector).val(data[outerKey][innerKey]);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="contact[actif]" name="contact[actif]">
<input type="text" id="contact[sql]" name="contact[sql]">
<input type="text" id="interlocuteur[actif]" name="interlocuteur[actif]">
<input type="text" id="interlocuteur[sql]" name="interlocuteur[sql]">

If you do know the key names, then it's simply a case of accessing the object to retrieve the values.

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

2 Comments

How can I do for the foreach do work on the same order that my JSON ?
You can't as the order of properties in an object is not guaranteed. If you require that it is you will need to use an array instead of an object.
0

Using JavaScript:

document.getElementById("contact[actif]").value = contact.actif;
document.getElementById("contact[sql]").value = contact.sql;

document.getElementById("interlocuteur[actif]").value = interlocuteur.actif;
document.getElementById("interlocuteur[sql]").value = interlocuteur.sql;

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.