从对象数组中,如果对象的valueA与变量匹配,如何获取该对象的valueB?

时间:2019-10-18 04:47:39

标签: javascript arrays find

假设您有一个对象数组。

let dogs = [
  { 
    colour: "blue",
    breed: "poodle"
  },
  { 
    colour: "yellow",
    breed: "poodle"
  },
  { 
    colour: "red",
    breed: "laborator"
  }
];

按品种匹配时如何获得颜色?

我尝试过:

let myFavouriteColour = dogs.find(dog => {
   if (dog.breed === "laborator") return dog.colour
});

这将返回一个符合以上条件的对象;我只希望它返回colour属性中的值。

2 个答案:

答案 0 :(得分:2)

一旦.find匹配,返回true(或仅返回相等测试),然后访问.find之外的匹配对象的属性:

let dogs = [
  { 
    colour: "blue",
    breed: "poodle"
  },
  { 
    colour: "yellow",
    breed: "poodle"
  },
  { 
    colour: "red",
    breed: "laborator"
  }
];

const laborator = dogs.find(dog => dog.breed === "laborator");
if (laborator) {
  const myFavouriteColour = laborator.colour;
  console.log(myFavouriteColour);
}

答案 1 :(得分:1)

Array.find()是JavaScript中的内置函数,用于获取 第一个元素 中的对象(或值,如果它是值的数组)满足提供条件的数组。您可以访问返回结果的属性。

let dogs = [
  { 
    colour: "blue",
    breed: "poodle"
  },
  { 
    colour: "yellow",
    breed: "poodle"
  },
  { 
    colour: "red",
    breed: "laborator"
  }
];

let myFavouriteColour = dogs.find(dog => dog.breed === "laborator").colour;
console.log(myFavouriteColour);