检查是否存在对象数组

时间:2019-09-02 06:58:36

标签: javascript

我有一个对象数组:

items: [
  { name: "Cheese Puffs", price: 3 },
  { name: "Can of Soda", price: 1.75 }
];

我想做类似items["cheesePuffs"] === true的事情。但是由于它在数组中,因此无法正常工作。

7 个答案:

答案 0 :(得分:4)

您想要的是Array.find()

myArrOfObjects.find(el => el.cheesePuffs);

假设您要查找的属性为true,则返回元素{cheesePuffs: "yes"}为true。如果找不到,则为undefined

答案 1 :(得分:3)

您可以使用somehasOwnProperty,如果您需要实际值而不是布尔值,则可以使用find而不是some

const myArrOfObjects = [{
  cheesePuffs: "yes"
},
{
  time: "212"
}];

let findByName = (name) => {
  return myArrOfObjects.some(obj=> {
    return obj.hasOwnProperty(name)
  })
}

console.log(findByName("cheesePuffs"))
console.log(findByName("time"))
console.log(findByName("123"))

答案 2 :(得分:2)

您可以使用find

let exist = myArrOfObjects.find(o => o.cheesePuffs === 'yes')

答案 3 :(得分:2)

好的简单解决方案

尝试

const x = [{}];

if(x.find(el => el.cheesePuffs) == undefined)
  console.log("empty objects in array ")
  
const myArrOfObjects = [{
  cheesePuffs: "yes"
},
{
  time: "212"
}];


if(myArrOfObjects.find(el => el.cheesePuffs) == undefined)
  console.log("empty objects in array ")
  else
  console.log("objects available in array ")

答案 4 :(得分:2)

尝试以下代码。它将返回名称与“ Cheese Puffs”匹配的对象。

let items = [{
    name: "Cheese Puffs",
    price: 3
  },
  {
    name: "Can of Soda",
    price: 1.75
  }
];

let itemExist = items.find(x => x.name === 'Cheese Puffs');

if (itemExist) {
  console.log(itemExist);
} else {
  console.log("Item not Exist");
}

答案 5 :(得分:2)

作为建议,您还可以决定不使用数组,而是使用json对象,其中每个项目的索引是对象的唯一名称(在示例中,“ cheesePuffs”标识为“ Cheese Puffs”)< / p>

let items = {
"cheesePuffs": {name: "Cheese Puffs",price: 3},
"canOfSoda": {name: "Can of Soda",price: 1.75},
};

console.log("exist: ", items.cheesePuffs!== undefined)
console.log(items.cheesePuffs)
// can also access to item in this way:
console.log(items["cheesePuffs"])

console.log("not exist", items.noCheesePuffs!== undefined)
console.log(items.noCheesePuffs)

答案 6 :(得分:1)

首先,您有一个对象数组,因此不能简单地使用

myArrOfObjects["cheesePuffs"]

因为数组需要索引,所以它应该为myArrOfObjects[0]["cheesePuffs"]

let items = [
  { name: "Cheese Puffs", price: 3 },
  { name: "Can of Soda", price: 1.75 }
];


let filter = items.find( el => el.price === 3 );

console.log(filter);

另一种方法

  let items = [
      { name: "Cheese Puffs", price: 3 },
      { name: "Can of Soda", price: 1.75 }
    ];


    let filter = items.filter( el => el.price === 3 );

    console.log(filter);