Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

I also tried

var.includes("value")

without the .flat() but that would only return if the top level includes it.

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.

question from:https://stackoverflow.com/questions/65516922/does-subarray-contain-a-certain-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
63 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use flatMap to extract all nested values into a single flat array first:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...