0

this is my array in js:

const array = [
  {
    id: 1,
    userId: 1,
    title: 'test1',  
  },
  {
    id: 2,
    userId: 1,
    title: 'test2',  
  },
  {
    id: 3,
    userId: 1,
    title: 'test3',  
  },
  {
    id: 4,
    userId: 1,
    title: 'test4',  
  }
]

and I only need to grab the object where I know its id and assign it to a variable. I know that I will need an object with id number 1 so I would like to:

const item = {
    id: 1,
    userId: 1,
    title: 'test1',  
  },
1

2 Answers 2

3

Use Array.find :

const array = [
  {
    id: 1,
    userId: 1,
    title: "test1"
  },
  {
    id: 2,
    userId: 1,
    title: "test2"
  },
  {
    id: 3,
    userId: 1,
    title: "test3"
  },
  {
    id: 4,
    userId: 1,
    title: "test4"
  }
];

const item = array.find(({ id }) => id === 1);

console.log(item);

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

Comments

1

Array has a filter function on its prototype that allows you to filter the values using a function, which gets passed each value in the array in turn. If the condition you specify in your function returns true, your value is returned.

So in this case:

const myArray = [
  {
    id: 1,
    userId: 1,
    title: 'test1',  
  },
  {
    id: 2,
    userId: 1,
    title: 'test2',  
  },
  {
    id: 3,
    userId: 1,
    title: 'test3',  
  },
  {
    id: 4,
    userId: 1,
    title: 'test4',  
  }
]

const idToFind = 1;

const foundValues = myArray.filter(item => item.id === idToFind)

Then if you knew only one value would you found, you would just take the first item in the foundValues array:

const foundItem = foundValues[0]

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.