首页 > 解决方案 > NodeJs - How to test if a value exists in an array of objects?

问题描述

I have an array of objects and want to know if a specific value already exists inside this array.

let arrTest = []
let arrDt = [
  {"attrJSON": "01"},
  {"attrJSON": "01"},
  {"attrJSON": "02"},
  {"attrJSON": "02"},
  {"attrJSON": "03"},
  {"attrJSON": "04"},
  {"attrJSON": "04"},
  {"attrJSON": "05"},
  {"attrJSON": "05"},
  {"attrJSON": "04"}
]

for(let i = 0; i < 10; i++)
{
  console.log(arrDt[i].attrJSON) //01 01 02 02 03 04 04 05 05 04 
  console.log((arrDt[i].attrJSON in arrTest)) //false false false false false false false false false false
  
  if(!(arrDt[i].attrJSON in arrTest)) {
    arrTest.push(arrDt[i].attrJSON)
  }
}
  console.log(arrTest)

I think the previous code will not work because the value to be tested is in an object property, not a value of an array. The goal here is to build an array arrTest of unique objects, like:

arrTest = [
"01",
"02",
"03",
"04",
"05",
]

How could I achieve this task?

标签: node.jsarraysobject

解决方案


推荐阅读