![](/img/trans.png)
[英]How to check whether all the key & value of a JS Object exist in the another JS object in JavaScript?
[英]Checking whether key and value exist in Javascript object
假設我有:
var original = {
0: {
id : 158
},
1: {
id : 159
}
}
var newSeries = {
0: {
id : 158,
name: "Jason",
lastname: "Smith",
status : "active"
},
1: {
id : 159 ,
name: "Rebecca",
lastname: "Smith",
status : "terminated"
}
}
並且我想知道例如newSeries
id
#158 newSeries
存在於original
,我將如何去做? 我找到了使用in
運算符的部分解決方案,但只比較了它們的鍵,而不是鍵和值。
如果您打算做很多這樣的處理,我建議您使用underscorejs 。 它具有通過傳遞lamda函數,過濾,排序,合並,聚合以及許多其他功能來查找值的方法
使用underscorejs,它的一線便是:
_(original).find(function(x) { return x.id == 159; })
嘗試這個:
for (var n in newSeries) {
console.log('id ' +
newSeries[n].id +
' exists: ' +
(original[n].id === newSeries[n].id));
}
您將必須遍歷每個鍵和值以測試id是否存在。
例如
var myId = 158;
for (var key in original) {
if (original[key].id === myId) {
// here your id has been found
}
}
如果您不想像這樣遍歷對象,則必須稍微更改數據結構。 您可以將id用作原始對象中的鍵,並按以下方式搜索它:
var original = {
158: {
id : 158
},
159: {
id : 159
}
};
var myId = 158;
if (myId in original) {
// here your id has been found
}
如果您以ES5為目標:
function isValueInObject(value, object) {
return Object.keys(object).map(function (key) {
return object[key];
}).some(function (_value) {
return _value === value;
});
}
console.log(isValueInObject('bar', {foo: 'bar'})) // true
console.log(isValueInObject('baz', {foo: 'bar'})) // false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.