javascript 获取属性数组中具有特定键值的对象

ax6ht2ek  于 2022-12-17  发布在  Java
关注(0)|答案(2)|浏览(198)

我需要找到数组的所有对象,这些对象在“模式”属性中包含颜色“绿色”。

let arr = [
  {
    "type": "One",
    "mode": [{ 
        "color": "blue", 
        "size": "L"
      }
    ]
  }, {
    "type": "Two",
    "mode": [{ 
        "color": "green", 
        "size": "M"
      }
    ]
  },{
    "type": "Three",
    "mode": [{ 
        "color": "green", 
        "size": "L"
      }
    ]
  },{
    "type": "Four",
    "mode": [{ 
        "color": "red", 
        "size": "XS" 
      }
    ]
  }
];
    
    
let result = arr.indexOf(arr.find(function(el,index){
  return el['mode'][0].color === 'green';
}))

console.log(result);

目前只能获取索引。
我希望在输出中得到类似下面的内容:

[
       {
        "type": "Two",
        "mode": [{ 
            "color": "green", 
            "size": "M"
          }
        ]
      },{
        "type": "Three",
        "mode": [{ 
            "color": "green", 
            "size": "L"
          }
        ]
      }
    ]
r7xajy2e

r7xajy2e1#

使用Array.prototype.filterArray.prototype.some搜索内部数组

const filterByModeColor = (arr, color) =>
  arr.filter(ob => ob.mode?.some(o => o.color == color));

const myArr = [
  {"type": "One", "mode": [{"color": "blue", "size": "L"}]},
  {"type": "Two", "mode": [{"color": "green", "size": "M"}]},
  {"type": "Three", "mode": [{"color": "green", "size": "L"}]},
  {"type": "Four", "mode": [{"color": "red", "size": "XS"}]}
];

const filtered = filterByModeColor(myArr, "green");
console.log(filtered);

要额外过滤内部 "mode": 数组,请改用Array.prototype.reduce

const filterByModeColor = (arr, color) => arr.reduce((acc, obj) => {
  const mode = obj.mode.filter(o => o.color === color);
  mode.length && acc.push({...obj, mode});
  return acc;
}, []);

const myArr = [
  {"type": "One", "mode": [{"color": "blue", "size": "L"}, {"color": "green", "size": "L"}]},
  {"type": "Two", "mode": [{"color": "green", "size": "S"}, {"color": "green", "size": "M"}, {"color": "red", "size": "Xl"}]},
  {"type": "Three", "mode": [{"color": "yellow", "size": "L"}, {"color": "blue", "size": "XL"}]},
  {"type": "Four", "mode": [{"color": "red", "size": "XS"}]}
];

const filtered = filterByModeColor(myArr, "green");
console.log(filtered);
zzlelutf

zzlelutf2#

最佳方法是使用两种阵列方法:filtersome
filter允许你迭代数据数组,只返回那些符合特定条件的对象,在这个例子中,它是mode数组中是否有任何对象的颜色是“绿色”。

let arr=[{type:"One",mode:[{color:"blue",size:"L"}]},{type:"Two",mode:[{color:"green",size:"M"}]},{type:"Three",mode:[{color:"green",size:"L"}]},{type:"Four",mode:[{color:"red",size:"XS"}]}];

// Iterate over the array of objects
const result = arr.filter(obj => {

  // If some of the objects in the `mode` array
  // have a color property with the value green
  // return `true` - and that object will be returned
  // by `filter`
  return obj.mode.some(m => m.color === 'green');
});

console.log(result);

相关问题