Say I have an array of objects {key:string} where all the keys-value pairs are unique (keys or values are allowed to the same in different objects, but the same key value pair)
const arr = [{a_1:"val_1"}, {a_2:"val_2"}, ..., {a_n:"val_n"}];
and I have a target object
const target = {a_i: "val_i"};
I want to find if target
exists in arr
ie if it's key and value match a certain object in arr
. If true, then I want the object from arr
to be returned.
example: (Edited)
const target = {foo: "bar"};
const arr = [{foo: "bar"}, {corona: "COVID-19"}, {foo: "notBar"}, {notFoo: "bar"}];
In this example, the search of target
on arr
will return {foo:"bar"}
from arr
.
Note:
arr.find(ob => ob === target);
returns undefined.
Those 2 have different references. Maybe with JSON.stringify()
it can work.
const target = {foo: "bar"}; const arr = [{foo: "bar"}, {corona: "COVID-19"}]; const result = arr.find(ob => JSON.stringify(ob) === JSON.stringify(target)); console.log(result);
Or a better option to use .every()
as the following:
const target = {foo: "bar"}; const arr = [{foo: "bar"}, {corona: "COVID-19"}]; const keysT = Object.keys(target); const result = arr.find(e => { const keysE = Object.keys(e); return keysE.length === keysT.length && keysE.every(k => e[k] === target[k]) }); console.log(result);
I hope this helps!
that will do it if keys are not in order. But not if the key values of the target object objects itself.
const target = {foo: "bar"};
const arr = [{foo: "bar"}, {corona: "COVID-19"}];
arr.find(ob => {
for (key in target) {
if (!(key in ob)) return false;
if (ob[key] !== target[key]) return false;
}
return true;
});
Edit:
With "keys are not in order", I mean:
const target = {foo: "bar", bar: "foo"};
const arr = [{bar: "foo", foo: "bar"}, {corona: "COVID-19", foo: "bar"}];
If there's a single key/value pair in your target option, you may use Array.prototype.some()
to look up through your source array (until match is found) and extract target key/value, using Object.entries()
, like that:
const arr = [{a_1:"val_1"}, {a_2:"val_2"}, {a_n:"val_n"}], target = {a_2: "val_2"}, [[targetKey, targetValue]] = Object.entries(target), hasMatch = arr.some(item => targetKey in item && item[targetKey] == targetValue) console.log(hasMatch)
.as-console-wrapper{min-height:100%;}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.