如何检查数组中的特定对象(数据)?

时间:2018-12-26 11:31:32

标签: javascript html css vue.js vuejs2

我是编程方面的初学者,目前遇到问题。我有一个包含4个项目的数组(您可以在下面的“代码”部分看到该数组),所有四个项目都有其特定的ID(1-4)。

我要编程的东西是一种为每个Array项目运行单独的Code的方法。我以为我可以通过在if语句中简单地检查id(在每个项目中都是单独的)来解决此问题。但是我该怎么办?

如果有人有更好的主意,他可以肯定地告诉我该ID。

最好的问候约翰。

{ id: 1, name: 'BMW', price: 250, quantity: ''},

{ id: 2, name: 'Google', price: 110, quantity: ''},

{ id: 3, name: 'Apple', price: 1000, quantity: ''},

{ id: 4, name: 'Twitter', price: 50, quantity: ''}

4 个答案:

答案 0 :(得分:0)

您可以使用if语句实现此目的。有不同的方法,但是基本方法将保持不变。遍历数组中的每个元素,然后检查id。您可以使用传统的for循环,也可以使用somefilter等方法。

答案 1 :(得分:0)

您可以使用简单的for循环简单地迭代数组,并检查id是否等于给定的id,然后返回整个对象。如果id不匹配,它将返回undefined。考虑以下代码片段:

let array = [{ id: 1, name: 'BMW', price: 250, quantity: ''},

{ id: 2, name: 'Google', price: 110, quantity: ''},

{ id: 3, name: 'Apple', price: 1000, quantity: ''},

{ id: 4, name: 'Twitter', price: 50, quantity: ''}];

function getValue(id)
{
  for( var index=0;index<array.length;index++){
     if( array[index].id === id){
        return array[index];
     }
  };
}

console.log(getValue(1));
console.log(getValue(5));

答案 2 :(得分:0)

使用filter()浏览并比较每个项目的ID和所需的文本-请注意,然后我可以返回相关对象(例如-如果要显示名称)-或文本字符串如果它不存在。

您还可以在其中添加逻辑以确保ID唯一-即,如果为给定ID找到多个结果-那么您需要编辑重复项的ID。

let items = [
  { id: 1, name: 'BMW', price: 250, quantity: ''},
  { id: 2, name: 'Google', price: 110, quantity: ''},
  { id: 3, name: 'Apple', price: 1000, quantity: ''},
  { id: 4, name: 'Twitter', price: 50, quantity: ''}
]

function findItem(id){
  
  var foundItem = items.filter(function(item){
    return(item.id == id) 
   });
   
   if(foundItem.length > 0) {
    return foundItem[0];
   } else {
    return "Item not found";
   }
}

console.log(findItem('1')); // returns the object of the BMW
console.log(findItem('6')); // returns "Item not found"

答案 3 :(得分:0)

据我了解,您想为数组中的不同项目运行单独的代码段。如果数组的元素是固定的,即它们不变,那么您可以为每个项目编写不同的代码作为函数,并将其作为属性添加到相应的项目中。

请参见以下示例:

let BMWFunction = function(){
   console.log('BMW!');
}

let googleFunction = function(){
   console.log('Google!');
}

let myArray = [
   { id: 1, name: 'BMW', price: 250, quantity: '', code: BMWFunction},
   { id: 2, name: 'Google', price: 110, quantity: '', code: googleFunction }
]

for (let i = 0; i < myArray.length; i++){
   myArray[i].code();
}

然后,对于在数组中循环通过的每个项目,都可以调用关联的代码属性。

相关问题