如何从javascript中的数组和对象比较中筛选值?

时间:2019-05-08 11:12:31

标签: javascript arrays

在这里,我有一个对象和一个数组,我想过滤比较数组和对象的值,

对象具有多个值,请参见下面的代码Reader, Author, Publisher..,在数组Author and Reader中,我想将它们进行比较,并希望得到wanted result :- [1, 8]的这种类型的结果 这是我的对象

object1 = { 1: "Reader"
  8: "Author"
  3: "Publisher"
  9: "Site Editor"
  11: "Guest"
  12: "Editor"
  13: "Designer"
  14: "Publicist"
}

这是我的数组

array1 = ["Reader", "Author"]

6 个答案:

答案 0 :(得分:2)

您可以filter对象的键并使用includes

检查键在数组中是否有值

const object1 = {
  1: "Reader",
  8: "Author",
  3: "Publisher",
  9: "Site Editor",
  11: "Guest",
  12: "Editor",
  13: "Designer",
  14: "Publicist"
};

const array1 = ["Reader", "Author"]

const keys = Object.keys(object1).filter(k => array1.includes(object1[k]))

console.log(keys)

答案 1 :(得分:2)

您可以使用Map并通过使用对象条目中的切换键/值来返回值。

结果是字符串,因为对象的键是字符串或符号。

var object = { 1: "Reader", 8: "Author", 3: "Publisher", 9: "Site Editor", 11: "Guest", 12: "Editor", 13: "Designer", 14: "Publicist" },
    array = ["Reader", "Author"],
    result = array.map(
        Map.prototype.get,
        new Map(Object.entries(object).map(([k, v]) => [v, k]))
    );

console.log(result);

答案 2 :(得分:1)

我认为该解决方案可能会对您有所帮助

 var values = Object.keys(object1).filter(key => {
   return array1.indexOf(object1[key]);
 });
console.log(values);

答案 3 :(得分:1)

这可以使用数组过滤器映射和查找。

object1 = { 1: "Reader",
  8: "Author",
  3: "Publisher",
  9: "Site Editor",
  11: "Guest",
  12: "Editor",
  13: "Designer",
  14: "Publicist",
}


array1 = ["Reader", "Author"]

let result=Object.values(object1)

let finalresult=array1.filter(ele=>result.includes(ele)).map(element=>Object.keys(object1).find(key => object1[key] === element))
console.log(finalresult)

答案 4 :(得分:1)

您可以遍历对象,并检查该值是否存在于array1中。如果是这样,则将键推到数组

let obj = {
  1: "Reader",
  8: "Author",
  3: "Publisher",
  9: "Site Editor",
  11: "Guest",
  12: "Editor",
  13: "Designer",
  14: "Publicist",
}

let array1 = ["Reader", "Author"];
let newArry = [];

for (let keys in obj) {
  if (array1.includes(obj[keys])) {
    newArry.push(keys)
  }
}
console.log(newArry)

答案 5 :(得分:0)

我认为以下代码可能对您有所帮助:

array1=[object1.1,object1.2]

属性对象1不是数组,它是一个对象,每个对象都有一个属性,这里的object1中的值'1'是一个属性,'Reader'是该属性的值,您可以通过以下方式获取该对象的每个值点和属性名称。