【问题标题】:Fetching Objects from Array by passing key & value in javascript通过在javascript中传递键和值从数组中获取对象
【发布时间】:2019-11-21 01:51:57
【问题描述】:

这是我的对象数组。我想通过在函数中传递查询来过滤对象。

const products = [{
    name: "A",
    color: "Blue",
    size: 50
  },
  {
    name: "B",
    color: "Blue",
    size: 60
  },
  {
    name: "C",
    color: "Black",
    size: 70
  },
  {
    name: "D",
    color: "Green",
    size: 50
  }
];

我想要的输出将从我传递的查询中过滤出来,函数可以是任何东西

{
  name: "A",
  color: "Blue",
  size: 50
}, {
  name: "C",
  color: "Black",
  size: 70
}

这是我将传递给函数的查询对象

const filter = {
  color: ["Blue", "Black"],
  size: [70, 50]
};

这是我的函数,我可以将其分配给其他变量并将其用于进一步的操作

const filteredData = filterIt(products, filter);

【问题讨论】:

  • 这就是我遇到的问题。 //Function const filterIt = (data, filter) => { //console.log(filter); for (let i = 0; i
  • 最好将其添加到可以正确格式化的问题中,而不是很难阅读的评论
  • 好的.. 实际上我不确定我的方法,因为我是 javascript 新手,所以没有发布
  • 如果某个值的颜色为Blue,但大小与7050 不同,该怎么办?是否应该包括在内?
  • ya...抱歉最后一条评论我正在寻找包含不同大小对象的代码

标签: javascript arrays object javascript-objects


【解决方案1】:

这是另一种选择:

function filterIt(products, filter) {
  return products.filter(p => {
    for (const k in filter) {
      if (filter[k].indexOf(p[k]) === -1) {
        return false;
      }
    }
    return true;
  })
}

查看Demo

如果您想在逻辑中使用 OR 而不是 AND,之前修改的函数将是:

function filterIt(products, filter) {
  return products.filter(p => {
    for (const k in filter) {
      // if a value of any property of the product is contained in a filter array, include it
      if (filter[k].indexOf(p[k]) !== -1) {
        return true;
      }
    }
    return false;
  })
}

也请查看Demo :)

【讨论】:

  • 感谢您的帮助,但我想知道您已经问过的一件事。就像我想包含蓝色但大小不同的值一样。同时传递相同的查询
  • @jeetdeveloper 查看我的答案已更新,包括另一个演示:stackblitz.com/edit/…。请注意,这是所有过滤器之间的 OR,而不仅仅是 colorsize。如果您有任何疑问,请告诉我;)
  • 如果你想进行更复杂的比较,同时保持函数的通用性,你可能需要使filter对象更复杂,并在其中包含你想要执行的比较类型和内容像那样。否则,如果您只想坚持使用size,则可以直接检查size 属性,如果存在,则无论颜色是否匹配,都将该产品保留在最终结果中。
【解决方案2】:

您可以获取过滤器对象的条目并获取键和值以使用includes进行检查。

const
    filterBy = filter => o => Object.entries(filter).every(([k, v]) => v.includes(o[k])),
    filterIt = (array, filter) => array.filter(filterBy(filter)),
    products = [{ name: "A", color: "Blue", size: 50 }, { name: "B", color: "Blue", size: 60 }, { name: "C", color: "Black", size: 70 }, { name: "D", color: "Green", size: 50 }],
    filter = { color: ["Blue", "Black"], size: [70, 50] },
    filteredData = filterIt(products, filter);

 console.log(filteredData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案3】:

    const products = [{
        name: "A",
        color: "Blue",
        size: 50
      },
      {
        name: "B",
        color: "Blue",
        size: 60
      },
      {
        name: "C",
        color: "Black",
        size: 70
      },
      {
        name: "D",
        color: "Green",
        size: 50
      }
    ];
    const filter = {
      color: ["Blue", "Black"],
      size: [70, 50]
    };
    
    
    let filterIt = (products, filter) => {
    
      return products.filter(p => {
        
        //get all filter keys
        let keys = Object.keys(filter);
        
        let validkeys = [];
        
        keys.forEach(k=>{
          // check if filter property exist and includes filter value
          if(p.hasOwnProperty(k) && filter[k].includes(p[k])){
            validkeys.push(true);
          }
          
        })
        
        //check all filter matches
        return validkeys.length === keys.length;
        
      });
    
    }
    
    const filteredData = filterIt(products, filter);
    console.log("...filteredData", filteredData);

    【讨论】:

    • 感谢您的帮助,但我想知道您已经问过的一件事。就像我想包含蓝色但大小不同的值一样。同时传递相同的查询
    • @jeetdeveloper 然后推送有效的过滤键 validkeys.push(k);然后可以确定有效产品,如 return validkeys.includes('color')。这都是关于操纵过滤条件的。
    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    相关资源
    最近更新 更多