【问题标题】:Matching two arrays to create a third array匹配两个数组以创建第三个数组
【发布时间】:2016-11-22 17:08:26
【问题描述】:

我有一个数组:

var array = [black, white]

还有一个对象:

var object = [
    {color: black, hex: #000000},
    {color: white, hex: #ffffff},
    {color: red, hex: #ff0000}
]

我想做的是从数组和对象中匹配的颜色创建一个新对象,所以在这个例子中,新对象是:

var object = [
    {color: black, hex: #000000},
    {color: white, hex: #ffffff}
]

【问题讨论】:

  • 您可以创建一个新的数组 objectFiltered,循环对象并对 array.indexOf(object[i].color) > -1 进行条件检查,如果为真,则将当前索引推送到 objectFlitered。

标签: javascript jquery arrays object match


【解决方案1】:

您可以为此使用filter

var arr = ["black", "white"];
var obj = [
    {color: "black", hex: "#000000"},
    {color: "white", hex: "#ffffff"},
    {color: "red", hex: "#ff0000"}
];

var res = obj.filter(itm => arr.includes(itm.color));
console.log(res); //[{color: "black", hex: "#000000"}, {color: "white", hex: "#ffffff"}]

【讨论】:

  • filterincludes(IE 不支持)
  • @j08691 IE >=9 支持filterindexOf。如果 OP 想在 ES
【解决方案2】:

你可以filter对象这样:

var array = ['black', 'white']

var object = [
    {color: 'black', hex: '#000000'},
    {color: 'white', hex: '#ffffff'},
    {color: 'red', hex: '#ff0000'}
]

var result = object.filter(function(entry) {
  return array.indexOf(entry.color) > -1;
})

console.log(result);

【讨论】:

    【解决方案3】:

    使用过滤器:

    var array = ['black', 'white'];
    var objectArray = [
        {color: 'black', hex: '#000000'},
        {color: 'white', hex: '#ffffff'},
        {color: 'red', hex: '#ff0000'}
    ];
    
    var result = objectArray.filter(function(item) {
        return array.some(function(i) {
            return i === item.color;
      })
    });
    
    
    console.log(result);
    

    注意,我必须在您的一些示例数据中添加引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-09
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多