问题描述
首先我还在学习,所以请保持柔和:)我有一个JSON响应,我想选择一些特定的元素.我试图在对象内获取某些具有特定名称的元素,并想测试它是否与预定义名称匹配.这些是具有特定名称的产品规格,例如长度",宽度"等.
First of all I'm still learning so please be gentle :)I have a json response where I want to select some specific elements.I'm trying to get some elements with a specific name inside an object and want to test if it matches a predefined name. These are product specifications with a specific name like "length", "width" etc.
我很难找到这些特定的名称,如果找到它们,则获取其值"属性.
I'm having trouble to find those specific names and if they are found get their "value" attribute.
所以我有这个:
JSON响应:
{
"product": {
"specs": {
"231638": {
"id": 231638,
"title": "Length (mm)",
"value": "1200"
},
"231641": {
"id": 231641,
"title": "Width (mm)",
"value": "800"
},
"231644": {
"id": 231644,
"title": "Height (mm)",
"value": "144"
} //etc etc
现在,我只想从规范长度"和高度"中获取两个value
属性.因此,首先我必须查看这两个名称是否存在并且匹配"length"和"height",如果是,则获取它们的value
属性.那是我需要帮助的地方.
Now I want to grab only the two value
attributes from specifications "length" and "height". So first I have to look if those two names are present and matches "length" and "height" and if so grab their value
attributes. That's where I need some help.
最终结果必须是
<div class="somediv">
<span class="width">1200</span>
<span class="height">144</span>
</div>
所以我有这个:
$.getJSON(url', function(data){
var specsHtml = [];
$.each(data.product.specs, function(index, spec){
// in here I need to test if the name of the spec equals "length or Height".
specsHtml.push(spec.value);
});
specsHtml = specsHtml.join('');
}
container.find('.product-bottom .measurements span').html(specsHtml);
});
我完全被困在这里.我已经尝试过类似的事情:
I'm completly stuck in here. I have tried things like:
(spec.hasOwnProperty("title"));
或
var specs = [];
data.product.specs.forEach(data.product.specs => {
if (data.product.specs)
for (var spec in data.product.specs)
specs.push(spec);
})
任何帮助,我们都感激不尽:)
Any help greatly appreciated :)
推荐答案
var data = {
"product": {
"specs": {
"231638": {
"id": 231638,
"title": "Length (mm)",
"value": "1200"
},
"231641": {
"id": 231641,
"title": "Width (mm)",
"value": "800"
},
"231644": {
"id": 231644,
"title": "Height (mm)",
"value": "144"
} //etc etc
}
}
};
var length = 0, width = 0, height = 0,
reLength = /length/i,
reWidth = /width/i,
reHeight = /height/i;
$.each(data.product.specs, function (specId, spec) {
if (reLength.test(spec.title))
length = spec.value;
else if (reWidth.test(spec.title))
width = spec.value;
else if (reHeight.test(spec.title))
height = spec.value;
});
var html = '<div class="somediv">' +
'<span class="width">w: ' + width + '</span>' +
'<span class="height">h: ' + height + '</span>' +
'<span class="length">l: ' + length + '</span>' +
'</div>';
$(document.body).html(html);
.somediv > span { padding: 10px; display:inline-block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这篇关于选择对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!