我有一个对象数组,其中一个属性是一个没有键的值数组,我试图过滤并检查嵌套数组中的匹配值。以下是一个对象的示例:
[ 0:
{ fiber_phases: ["45", "46"],
id: 1,
label: "3200 to 3299 1 1/2 ST N",
max_number: "3299",
min_number: "3200",
parsed_hash: "4028c7befc61ba4d07189f6ba99de35f",
street: "1 1/2 ST N"
}
]
这是迄今为止我的 JavaScript 代码:
return this.blocks
.filter((block) => block.fiber_phases === fiberPhase)
.map(({id, label, max_number, min_number, street, parsed_hash, fiber_phases}) => ({id: id, label: label, max_number: max_number, min_number: min_number, street: street, parsed_hash: parsed_hash, fiber_phases: fiber_phases}))
很明显,我实际上并没有进入嵌套数组,但我无法访问它。
最佳答案
如果您想过滤主数组,使其仅包含在其 optical_phases
数组中任意位置具有 opticalPhase
的对象,则可以使用 filter
与 includes
在谓词中:
return this.blocks.filter(block => block.fiber_phases.includes(fiberPhase));
Array.prototype.includes
相对较新,但对于 polyfill 来说微不足道(请参阅上面的链接)。或者,如果您不想,indexOf
也可以:
return this.blocks.filter(block => block.fiber_phases.indexOf(fiberPhase) !== -1);
请注意,这将返回一个与原始数组共享对象的新数组。如果您想复制它们,您可以添加
.map(entry => Object.assign({}, entry))
到它,或者与一些Stage 4 syntax这将出现在 ES2018 规范中:
.map(entry => ({...entry}))
无论哪种方式,它都是浅拷贝(fibre_phases
数组将被共享)。
根据需要进行调整。
关于JavaScript 通过嵌套数组过滤对象数组并检查嵌套数组内的变量匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016084/