简体   繁体   English

查找并更新 JSON 中的特定对象

[英]Find and update a specific object in JSON

I am generating a form that is constructed from JSON.我正在生成一个由 JSON 构造的表单。 I've successfully created the form, but I am now trying to figure out how to update the specific item in JSON from the user input.我已经成功创建了表单,但我现在想弄清楚如何从用户输入中更新 JSON 中的特定项目。 I've seen this question asked using node and underscore, etc but I would like to accomplish this with vanilla JS or jQuery.我已经看到使用 node 和下划线等提出的这个问题,但我想用 vanilla JS 或 jQuery 来完成这个。

I am trying to avoid modifying the JSON other than the values as it will need to be sent back in the same format, and I am able to find an item by its key or value, however the problem I have is that there are multiple k/v pairs in each object that I am using.我试图避免修改除值以外的 JSON,因为它需要以相同的格式发回,并且我能够通过其键或值找到一个项目,但是我遇到的问题是有多个 k /v 在我使用的每个对象中配对。 Here is an example object:这是一个示例对象:

var list = {
"parent": {
   "item" : {
      "id" : "a1b295",
      "name" : "sample name",
      "value" : "this is a sample value"
   }
}

My form elements come out as <input type="text" name="a1b295" value="this is a sample value" />我的表单元素显示为<input type="text" name="a1b295" value="this is a sample value" />

What I am trying to do is on submit, iterate through the form elements and update each object in the JSON.我想要做的是提交,遍历表单元素并更新 JSON 中的每个对象。 I am struggling to figure out how to look up the item by its id and then update the value key value pair for that object.我正在努力弄清楚如何通过其 id 查找项目,然后更新该对象的value键值对。

To be clear the data can have any number of nested children, and I need to go after the ones with specific IDs which I am already turning into form inputs.为清楚起见,数据可以有任意数量的嵌套子项,我需要追踪具有特定 ID 的子项,这些 ID 已经转换为表单输入。

Thank you.谢谢你。

This is what I have attempted but it returns a "can't access id of undefined" error.这是我尝试过的,但它返回“无法访问未定义的 id”错误。

function traverseData(data, obj)
  {
      for (var k in data)
      {
          if (typeof data[k] == "object" && data[k] !== null) {
              traverseData(obj[k], obj);
          } else if (!data.hasOwnProperty(k)) {
            continue;
          } else if (k = obj) {
            console.log(obj);
          }
      }
  }

  traverseData(data, $(this).attr('id'));

If I understand your question correctly, you have your form which was generated from a JSON array in the format described above, and want to update the values in that JSON array with new values that may have changed on submission.如果我正确理解了您的问题,您的表单是从上述格式的 JSON 数组生成的,并且想要使用提交时可能已更改的新值更新该 JSON 数组中的值。

The following code assumes your forms have been set up properly, and the text values have been updated with the values in the HTML section.以下代码假定您的表单已正确设置,并且文本值已使用 HTML 部分中的值进行更新。

jQuery solution jQuery 解决方案

 const json = [ { "item": { "id": "a1b295", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b296", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b297", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b298", "name": "sample name", "value": "this is a sample value" } } ] for (const item in json) { json[item].item.value = $('input[name="' + json[item].item.id + '"]').val() } console.log(json)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="a1b295" value="this is a sample value" /> <input type="text" name="a1b296" value="New sample value1" /> <input type="text" name="a1b297" value="New sample value2" /> <input type="text" name="a1b298" value="New sample value3" />

Vanilla Javascript solution原生 Javascript 解决方案

 const json = [ { "item": { "id": "a1b295", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b296", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b297", "name": "sample name", "value": "this is a sample value" } }, { "item": { "id": "a1b298", "name": "sample name", "value": "this is a sample value" } } ] for (const item in json) { json[item].item.value = document.querySelector('input[name="' + json[item].item.id + '"]').value } console.log(json)
 <input type="text" name="a1b295" value="this is a sample value" /> <input type="text" name="a1b296" value="New sample value1" /> <input type="text" name="a1b297" value="New sample value2" /> <input type="text" name="a1b298" value="New sample value3" />

These examples overwrite the value in the json variable that you can submit with your form.这些示例覆盖了您可以随表单提交的json变量中的值。 You should see that the json values have been updated to those in the HTML.您应该看到json值已更新为 HTML 中的值。

Javascript now supports for..in where you can loop through object keys: Javascript 现在支持for..in ,您可以在其中循环遍历对象键:

 let data = { "item" : { "id" : "a1b295", "name" : "sample name", "value" : "this is a sample value" } }; function traverseData(data, obj, newValue) { for (var k in data) { if (data.hasOwnProperty(k) && typeof data[k] == "object") { data[k] = traverseData(data[k], obj, newValue); } else if (k == obj) { console.log(obj); data[k] = newValue; } } return data } //single element $('input').blur(function(event){ data = traverseData(data, 'value', $(this).attr('value')); console.log(data); }); //multiple elements $('input').each(function (index) { let self = $(this); //to differenciate between elements self.blur(function(event){ data = traverseData(data, 'value', $(this).attr('value')); console.log(data); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="a1b295" value="this is a sample value 2" />

If I understand correctly, you could before submitting to json alter the input string and change values accordingly.如果我理解正确,您可以在提交到 json 之前更改输入字符串并相应地更改值。

If u need to compare to another JSON u could just compare values via function.如果您需要与另一个 JSON 进行比较,您可以通过函数比较值。

JSON is just a formated string. JSON 只是一个格式化的字符串。

I assume you have an array of objects.我假设你有一个对象数组。 So you basically can filter this array to find the object of which the id matches the corresponding input's name.所以你基本上可以过滤这个数组来找到id与相应输入名称匹配的对象。 And then update this object's value property with the input value.然后使用输入值更新此对象的 value 属性。

  const targetInput = document.getElementById('inputId')
  let newValue = targetInput.value
  let inputName = targetInput.name
  // We filter objects to find the one where id matches input's name
  let targetObject = objects.filter(i => i.item.id === inputName)
  targetObject[0].item.value = newValue
  console.log(targetObject)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM