我正在为我的学校项目制作条形码扫描仪,但我被卡住了。我不知道如何扫描这个对象。我有这个对象里面的对象,我需要扫描存储变量中的每个对象来检查它的条形码。
var storage = {
bolts: {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
brackets: {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
},
}
我有一个名为条形码的变量,我需要测试这个变量,如果它与其中一个相同。我尝试使用
for (var key in storage){
if (storage[key].barcode === barcode){
}
}
我想要最简单的方法。
答案 0 :(得分:1)
使用Object.keys:
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
以下是示例:
var storage = {
"bolts": {
barcode: 57263144,
price: 0.5,
name: 'Plain Brackets',
stock: 25,
},
"brackets": {
barcode: 13245627,
price: 0.2,
name: '100mm Bolts',
stock: 2,
}
}
var barcode = 57263144;
Object.keys(storage).forEach(function(key) {
if(storage[key].barcode === barcode) { console.log("do something")}
});
答案 1 :(得分:0)
使用递归函数来验证对象中是否存在更多节点,例如:
const complexObj = {
name: "nobody",
address: { number: 22, moreNumbers: [1,2,3,4,5] },
colors: ["green", "red"],
numbersAgain: { first: 1, second: 4 }
};
function scanObj(obj){
for (let i in obj) {
/*
*Do some verificatio, example:
*I'd like to verify all numbers and if the numbers is greater than 3:
*/
if(typeof obj[i] == "number" && obj[i] > 3){ console.log(obj[i]); }
if (typeof obj[i] === "object") {
scanObj(obj[i])
}
}
}
//call the method
scanObj(complexObj);
输出:22 4 5 4