gpt4 book ai didi

javascript - 访问对象的对象中的特定对象

转载 作者:行者123 更新时间:2023-11-29 19:15:30 25 4
gpt4 key购买 nike

我正在编写一个程序,它获取商店库存并搜索该库存中的特定商品,然后将这些商品放入一个数组中。库存都是一个对象,这个对象内的每个对象都是库存的一个项目。项目本身没有键——它们只是对象文字。因此,我一直在使用快速枚举(对于产品中的项目)循环遍历它们。每个项目看起来像这样:

{   id: 2759167427,   
title: 'Practical Silk Bag',
handle: 'practical-silk-bag',
vendor: 'Legros, Willms and Von',
product_type: 'Bag'
}

当且仅当该项目是键盘或计算机时,我试图做的是将项目对象推送到数组。为此,我尝试使用这样的方法:

var kbComps = [];

//loop through the inventory, looking for everything that is a keyboard or a computer
for (var key in products) {
var item = products[key];
for (var property in item) {
if (item[property].includes("Computer") || item[property].includes("Keyboard")) {
kbComps.push(item);
}
}
}

但是我收到一个错误,告诉我 includes 不是定义的方法,这意味着程序没有将 item[title] 识别为字符串,所以现在我被卡住了。我将如何避免这种情况?任何帮助表示赞赏。

大家好

最佳答案

已更新

我将实现更改为循环对象而不是数组。我想这就是您要找的。

Here is a working jsBin

可能这更简单一些,我相信它对你有用

// Products base data
var productsData = {
a: {
id: 2759167427,
title: 'Practical Silk Bag',
handle: 'practical-silk-bag',
vendor: 'Legros, Willms and Von',
product_type: 'Bag',
},
b: {
id: 2759167417,
title: 'Practical Silk Bag 2',
handle: 'practical-silk-bag-2',
vendor: 'Legros, Willms and Von 2',
product_type: 'Bag 2',
},
c: {
id: 2759167417,
title: 'Practical Silk Bag 3',
handle: 'practical-silk-bag-3',
vendor: 'Legros, Willms and Von 3',
product_type: 'Computer', // This product must be returned
},
d: {
id: 2759167417,
title: 'Practical Silk Bag 4',
handle: 'practical-silk-bag-4',
vendor: 'Legros, Willms and Von 4',
product_type: 'Keyboard', // This product must be returned
}
};


/**
* Function to find products by any condition
*/
function searchItemsByCondition(products, evaluateCondition) {

var ans = [];

for (var item in productsData) {
// Making sure the object has the property product_type
if (products[item].hasOwnProperty('product_type')) {
if (evaluateCondition(products[item])) {
ans.push(products[item]);
}
}
}
return ans;
}

function searchByKeyboardOrComputer(product) {
return (product.product_type === 'Computer') || (product.product_type === 'Keyboard');
}


// Call the function passing the evaluation function to satisfy.
// It should log only the items with 'Keyboard' or 'Computer' product_type
console.log(searchItemsByCondition(productsData, searchByKeyboardOrComputer));

希望这对你有用!

关于javascript - 访问对象的对象中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35713417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com