Home > front end >  Query an array of objects and return the target
Query an array of objects and return the target

Time:12-22

I need to find an object in an array by a key and value

I'm trying to do a search on an array of objects with for in. but I can not.

My input:

findObject[{ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 } }, { c: 3 }] //the last argument ({ c: 3 }) is the target

What I'm trying to return:

{ a: 1, b: { c: 3 } }

Note: The array of objects can have any object and the target too

CodePudding user response:

You can use Array.find to find the item in the array whose values contain an object whose c property is 3:

const arr = [{ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3 } }, { c: 3 }]
const result = arr.find(e => Object.values(e).some(k => k.c == 3))
console.log(result)

CodePudding user response:

What the OP is looking for is a find using deep equality (keys and values, including nested keys and values are equal). Even shallow equality is a deep topic in JS and applying it recursively is even deeper.

A fast but flawed idea is comparing JSON encodings for the two objects being compared. I wave a hand at that in the snippet, but prefer to use a utility that has thought through edge cases and probably executes fast.

function isEqual(a, b) {
  // not good, but quick to code:
  // return JSON.stringify(a) === JSON.stringify(b)
  
  // lodash has put some thought into it
  return _.isEqual(a, b)
}

// find the first object in  array with a value deeply equal to object
function findObject(array, object) {
  return array.find(el => {
    return Object.values(el).some(v => isEqual(v, object))
  })
}


let array = [{ a: 1, b: { c: 2 } }, { a: 1, b: { c: 3, d: { e: "hi" }} }];
let object = { c: 3, d: { e: "hi" }};

let result = findObject(array, object);
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

The OP asks to find the last object of an array as the target in the array up to that point. Adopt as follows...

// array is the array to search plus the last item is the thing to search for
let firstObjects = array.slice(0, -1)
let lastObject = array.at(-1)
let result = findObject(firstObjects, lastObject)
  • Related