简体   繁体   English

子数组是否包含某个值?

[英]Does subarray contain a certain value?

I have an array like this:我有一个这样的数组:

var = [
    {
        "a": "value",
        "b": "value2"
    },
    {
        "a": "value3",
        "b": "value4"
    }
    ...
]

I need to find if any of the subarrays contain a certain value.我需要查找是否有任何子数组包含特定值。

I tried我试过

var.flat().includes("value")

but that always returned false for some reason and .flat() didn't even flatten the array.但由于某种原因总是返回 false 并且.flat()甚至没有展平数组。

I also tried我也试过

var.includes("value")

without the .flat() but that would only return if the top level includes it.没有.flat()但只有在顶层包含它时才会返回。

I could do我可以做

var = [
    "a": [
        "value",
        "value3"
        ...
    ],
    "b": [
        "value2",
        "value4"
        ...
    ]
]

but I'd rather not since that'd require me to rewrite some code I already wrote.但我宁愿不这样做,因为那需要我重写一些我已经写过的代码。

Use flatMap to extract all nested values into a single flat array first:首先使用flatMap将所有嵌套值提取到单个平面数组中:

 const objs = [ { "a": "value", "b": "value2" }, { "a": "value3", "b": "value4" } ]; const values = objs.flatMap(Object.values); console.log(values.includes("value"));

You could iterate with some (it would stop the loop immediately when encounter the first value ), combine with Object.values (get array of values from an object) and .includes (to check if the array has value ),您可以迭代some (遇到第一个value时会立即停止循环),结合Object.values (从对象获取值数组)和.includes (检查数组是否有value ),

 const data = [ { a: "value", b: "value2", }, { a: "value3", b: "value4", }, ]; const valid = data.some((d) => Object.values(d).includes("value")); console.log(valid);

In your code, varr is already flatten array of objects.在您的代码中, varr已经是扁平化的对象数组。 Since you want to check in Object values.因为您想签入 Object 个值。 Use varr.map(Object.values).flat()使用varr.map(Object.values).flat()

 varr = [ { a: "value", b: "value2", }, { a: "value3", b: "value4", }, ]; console.log(varr.map(Object.values).flat().includes("value"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM