我有样本json对象的格式如下所示..
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}]
如果您看到前两个值与同一家庭相关,而第三个属于其他家庭 ...
我如何遍历这个完整的json对象,我需要提醒客户说这三个与同一个家庭无关......
请问有人请帮忙解决这个问题。 非常感谢提前
答案 0 :(得分:3)
您可以使用Array.prototype.every():
var test = result.every(function(item, index, array){
return item.family === array[0].family;
}); // true if all items in array have same family property set
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}];
var test = result.every(function(item, index, array){
return item.family === array[0].family;
});
alert(test);

答案 1 :(得分:1)
使用比较的简单循环。
for (var i= 1, first = result[0].family; i< result.length; i++) {
if (result[i].family !== first) {
alert('Family mismatch')
}
}
答案 2 :(得分:1)
您可以尝试类似
的内容var jsonString = '[{"value":"S900_Aru","family":"S400"},{"value":"S500_Aru","family":"S400"},{"value":"2610_H","family":"A650"}]';
var jsonData = $.parseJSON(jsonString);
var valueArray = new Array();
$.each(jsonData, function (index, value) {
valueArray.push(value['value']);
if ($.inArray(value['value'], valueArray)) {
alert('Duplicate Item');
return;
} else {
// Continue
}
});
答案 3 :(得分:1)
var result = [{"value":"S900_Aru","family":"S400"},
{"value":"S500_Aru","family":"S400"},
{"value":"2610_H","family":"A650"}]
var itemFamily = result[0].family;
var differs = false;
result.forEach(function(itm){
if (itemFamily != itm.family) {
differs = true;
}
});
alert((differs)?"Not related to the same family":"Related to the same family");
答案 4 :(得分:1)
我将存储family
的第一个值并使用every来检查数组的每个元素。
value = result[0].family;
function isSameFamily(element) {
return element.family == value;
}
a = result.every(isSameFamily);
https://jsfiddle.net/ejd64es0/
if(a){
alert("Same family")
}
else{
alert("Not Same family")
}
答案 5 :(得分:1)
您可以使用两个for循环来检查每个对象与另一个对象,并在两个系列不匹配时记录该消息。
for(var i=0;i<result.length-1;i++) {
for(var j=1;j<result.length;j++) {
if(result[i].family !== result[j].family)
console.log("Families do not match");
}
}
答案 6 :(得分:1)
您可以使用第一个元素检查每个元素,并返回Array#every()
的结果。
var result = [{ "value": "S900_Aru", "family": "S400" }, { "value": "S500_Aru", "family": "S400" }, { "value": "2610_H", "family": "A650" }],
related = result.every(function (a, i, aa) {
return aa[0] === a;
});
document.write(related);
&#13;