Jquery:访问多维JSON对象的值并在表单字段中指定

时间:2022-03-25 15:35:39

I am working with the huge Multidimensional JSON Objects where the user will submit the values in the form fields, then these values will be Stored in the database in JSON format like String

我正在使用庞大的多维JSON对象,用户将在表单字段中提交值,然后这些值将以JSON格式存储在数据库中,如String

Example of JSON:

JSON示例:

{
  "Cat": {
    "enabled": false,
    "Color": "#994c4c"
    "height":10,
    "eye": "blue",
  },
  "Dog": {
    "enabled": true,
    "typeOf": {
      "breed": "Affenpinscher"
    }
  },
  "Elephant": {
    "enabled": true,
    "food": {
      "type": {
        "fruits": true,
      }
    }
  }
}
 ........... continues...

User can create n number of JSON Strings like above with new properties and it will be stored in the Database

用户可以使用新属性创建n个上述JSON字符串,并将其存储在数据库中

So when the user Select the required JSON String from Database, i parse the string into JSON Objects in Jquery,

因此,当用户从数据库中选择所需的JSON字符串时,我将字符串解析为Jquery中的JSON对象,

But my biggest Problem is, I need to loop over these huge JSON Objects and retrieve the values from those Objects and i need to assign it in respective form fields

但我最大的问题是,我需要遍历这些巨大的JSON对象并从这些对象中检索值,我需要在各自的表单字段中分配它们

Examples of my From Fields:

我的From Fields的例子:

<select id="CatEnabled">
<option value="true">TRUE<option>
<option value="false">FALSE<option>
</select>

<input type="number" id="CatHeigt" min="20"/>

<input type="text" id="DogTypeOfBreed"/>

<select id="ElephantFoodTypeFruits">
<option value="true">TRUE<option>
<option value="false">FALSE<option>
</select>

My form fields will look something like the above, As My form field also contains huge number of fields almost more than 500+ fields,

我的表单字段将如上所示,因为我的表单字段还包含大量超过500多个字段的字段,

i am retrieving the JSON Objects something like this

我正在检索这样的JSON对象

            $.each(JSON.parse(cmsg), function (key, value) {
              if(key=="cat")
                 CatHeigt.val(value.height);
        });

the above for each loop is just a sample, i will loop inside a loop to get the values of JSON, as per my JSON Structure

上面的每个循环只是一个示例,我将在循环内循环以获取JSON的值,根据我的JSON结构

But only thing i need a simple Loop function to retrieve all the values and i need to assign it in all the respective form fields, i dont need something like this CatHeigt.val(value.height); because this process takes me too long for assigning all the 500+ form fields, instead i need simple solution

但只有我需要一个简单的循环函数来检索所有的值,我需要在所有相应的表单字段中分配它,我不需要像这样的CatHeigt.val(value.height);因为这个过程花了太长时间来分配所有500多个表单字段,而我需要简单的解决方案

1 个解决方案

#1


1  

You are currently using a PascalCased string of your object path as element ids. It would be easier if you could use a delimited string.

您当前正在使用对象路径的PascalCased字符串作为元素ID。如果你可以使用分隔的字符串会更容易。

Having done that, you can (1) split the string into an array based on that delimiter, (2) iterate that array and checking each item if it is an object property of your json object, (3) if found, assign that property to the object itself for the next iteration, (4) return the last object, (5) use that object value to assign to your form elements by iterating them as well.

完成后,您可以(1)将字符串拆分为基于该分隔符的数组,(2)迭代该数组并检查每个项目是否为json对象的对象属性,(3)如果找到,则赋予该属性对于下一次迭代的对象本身,(4)返回最后一个对象,(5)通过迭代它们来使用该对象值分配给表单元素。

Note: You have to be consistent in naming your elements, variables and properties. In your code as posted in the question, there is no consistency. For the example below, I have converting everything to lower case to normalize it. For all practical purposes, you will have to relook at that.

注意:在命名元素,变量和属性时必须保持一致。在问题中发布的代码中,没有一致性。对于下面的示例,我已将所有内容转换为小写以对其进行标准化。出于所有实际目的,您将不得不重新审视。

This snippet will make it clear to you:

这段代码会让你清楚:

var jsonString = '{"Cat": {"enabled": false, "Color": "#994c4c", "height":10, "eye": "blue" }, "Dog": { "enabled": true, "typeOf": {"breed": "Affenpinscher"}},"Elephant": {"enabled": true, "food": {"type": {"fruits": true}}}}';

var json = JSON.parse(jsonString.toLowerCase()); /* converted to lowercase */

function getProp(obj, str) {
    var arr = str.toLowerCase().split('-'); // splitting on delimiter 
    arr.forEach(function(item, idx) {       // iterate the split array 
        if (item in obj) obj = obj[item];   // if item is in object, assign this prop
        else return;                        // to the object. otherwise continue
    });                     
    return obj;                             // return the found prop as current obj
}

var $elems = $("input, select");            // jQuery set of all your elements
$elems.each(function() {                    // iterate this set of elements
    var id = this.id, 
        propValue = getProp(json, id);      // get the property by passing json and id
    $(this).val(propValue.toString());      // set the retreived property as val 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Cat-Enabled">
    <option value="true">TRUE</option>
    <option value="false">FALSE</option>
</select>
<br /><br />
<input type="number" id="Cat-Height" min="20"/>
<input type="text" id="Dog-TypeOf-Breed"/>
<br /><br />
<select id="Elephant-Food-Type-Fruits">
    <option value="true">TRUE</option>
    <option value="false">FALSE</option>
</select>

Demo Fiddle: http://jsfiddle.net/abhitalks/5ybu7nt3/1/

演示小提琴:http://jsfiddle.net/abhitalks/5ybu7nt3/1/

.

#1


1  

You are currently using a PascalCased string of your object path as element ids. It would be easier if you could use a delimited string.

您当前正在使用对象路径的PascalCased字符串作为元素ID。如果你可以使用分隔的字符串会更容易。

Having done that, you can (1) split the string into an array based on that delimiter, (2) iterate that array and checking each item if it is an object property of your json object, (3) if found, assign that property to the object itself for the next iteration, (4) return the last object, (5) use that object value to assign to your form elements by iterating them as well.

完成后,您可以(1)将字符串拆分为基于该分隔符的数组,(2)迭代该数组并检查每个项目是否为json对象的对象属性,(3)如果找到,则赋予该属性对于下一次迭代的对象本身,(4)返回最后一个对象,(5)通过迭代它们来使用该对象值分配给表单元素。

Note: You have to be consistent in naming your elements, variables and properties. In your code as posted in the question, there is no consistency. For the example below, I have converting everything to lower case to normalize it. For all practical purposes, you will have to relook at that.

注意:在命名元素,变量和属性时必须保持一致。在问题中发布的代码中,没有一致性。对于下面的示例,我已将所有内容转换为小写以对其进行标准化。出于所有实际目的,您将不得不重新审视。

This snippet will make it clear to you:

这段代码会让你清楚:

var jsonString = '{"Cat": {"enabled": false, "Color": "#994c4c", "height":10, "eye": "blue" }, "Dog": { "enabled": true, "typeOf": {"breed": "Affenpinscher"}},"Elephant": {"enabled": true, "food": {"type": {"fruits": true}}}}';

var json = JSON.parse(jsonString.toLowerCase()); /* converted to lowercase */

function getProp(obj, str) {
    var arr = str.toLowerCase().split('-'); // splitting on delimiter 
    arr.forEach(function(item, idx) {       // iterate the split array 
        if (item in obj) obj = obj[item];   // if item is in object, assign this prop
        else return;                        // to the object. otherwise continue
    });                     
    return obj;                             // return the found prop as current obj
}

var $elems = $("input, select");            // jQuery set of all your elements
$elems.each(function() {                    // iterate this set of elements
    var id = this.id, 
        propValue = getProp(json, id);      // get the property by passing json and id
    $(this).val(propValue.toString());      // set the retreived property as val 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Cat-Enabled">
    <option value="true">TRUE</option>
    <option value="false">FALSE</option>
</select>
<br /><br />
<input type="number" id="Cat-Height" min="20"/>
<input type="text" id="Dog-TypeOf-Breed"/>
<br /><br />
<select id="Elephant-Food-Type-Fruits">
    <option value="true">TRUE</option>
    <option value="false">FALSE</option>
</select>

Demo Fiddle: http://jsfiddle.net/abhitalks/5ybu7nt3/1/

演示小提琴:http://jsfiddle.net/abhitalks/5ybu7nt3/1/

.