[英]how do I find an object value in a javascript array?
What I want to do is check if the "content" is in my 'basket' before I add.我想要做的是在添加之前检查“内容”是否在我的“篮子”中。
I tried this, but I don't understand why it's not working:我试过这个,但我不明白为什么它不起作用:
function findById(source, tag, content) {
for (var i = 0; i < source.length; i++) {
if (source[i].tag === content) {
return source[i];
}
}
throw "Couldn't find content ";
}
Here is how I am using it:这是我如何使用它:
var basket = {};
var tag = 'someTag';
var content = 'Joe';
const key = randomFunctions.generateRandomString(); // eg ekkciiuekks
// find out if the content is already in the basket...
var result = findById(basket, tag, content);
if(!result){
// nope... so add it.
basket[key] = {[tag]:content};
}
ps.附: I would like to keep answer in pure javascript
我想用纯 javascript 保留答案
UPDATE更新
I am debugging and am getting 'undefined' when I hover over length:当我将鼠标悬停在长度上时,我正在调试并且得到“未定义”:
source.length
ANSWER回答
With a slight modification to https://stackoverflow.com/users/7668258/maciej-kocik answer, this works:对https://stackoverflow.com/users/7668258/maciej-kocik 的答案稍作修改,这有效:
function findById(source, tag, content) {
for (let key in source) {
let property = source[key];
if(property[tag] === content) {
return property[tag];
}
}
return null; // moved this OUTSIDE of for loop
}
The source.length
is undefined in your case. source.length
在您的情况下未定义。 You're adding a new object property, not a new array item.您正在添加一个新的对象属性,而不是一个新的数组项。
Try something like:尝试类似:
function findById(source, tag, content) {
for (let key in source) {
let property = source[key];
if(property[tag] === content) {
return property[tag];
}
throw "Couldn't find content";
}
}
const hasJoe = Object.values(basket).some( x => x.content === ‘Joe’);
(这不太正确,但我在用手机,编辑很棘手。这是它的要点。如果到那时你还没有答案,我会在使用真正的键盘时更新。)
Use for-in loop to iterate over the objects, we cannot use the traditional for loop.使用 for-in 循环遍历对象,我们不能使用传统的 for 循环。 Please find the logic below, i have changed it according to for-in loop.
请找到下面的逻辑,我已经根据 for-in 循环对其进行了更改。
var basket = {}; var tag = 'someTag'; var content = 'Joe'; const key = randomFunctions.generateRandomString(); // eg ekkciiuekks function findById(source, tag, content) { for (const property in source) { if (property === tag && source[property] === content) { return source[i]; } } throw "Couldn't find content "; } // find out if the content is already in the basket... var result = findById(basket, tag, content); if (!result) { // nope... so add it. basket[key] = { [tag]: content }; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.