0
const obj ={
  1: {name:"josh",age:2, symbol: "abc", id: 1},
  2: {name:"mike",age:4, symbol: "efg", id: 2}
}

const search = (input) => {
return Object.values(obj).filter(item => {
  return item.name.includes(input)
})
}

search("mi")
// returns: [ { name: 'mike', age: 4, symbol: 'efg', id: 2 } ]
  1. How can I access the found objects id (id:1)
  2. How can I get the found objects key (1: ...)

I am trying to find 1 and 2 of the object inside my array which matched my search input (see function)! In my filter I search for an object inside my array and see if one of those objects matches (or not) my search input. Then based on that I want to find the id of THAT object and its key Thanks!

2
  • Array.prototype.filter always returns an array, either empty or not. You can access items in this array by index. If you are totally sure there must be only one item in the resulting array, then probably access it by search('mi')[0]. The operation of accessing the first element is type-safe because Array#filter's signature guarantees that. Commented Jun 7, 2018 at 20:11
  • So it returns an array with an object so you reference the array and than the object? What is the issue you are having with that? Commented Jun 7, 2018 at 20:26

2 Answers 2

1

You had it right, except when you used Object.values you lost the object keys, check demo below

const obj ={
  1: {name:"josh",age:2, symbol: "abc", id: 1},
  2: {name:"mike",age:4, symbol: "efg", id: 2}
}

const search = (input) => {
  return Object.keys(obj).filter(key => {
    return obj[key].name.includes(input)
  })
  .map(foundKey => ({...obj[foundKey], key: foundKey }))
}


const result = search("mi")
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

1

Change the search for this:

const search = input => Object.values(obj).findIndex(item => item.name.includes(input));

Your Search:

const index = search('mike');

Your ID:

const id = Object.keys(obj)[index];

Your Item:

const item = obj[id];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.