2

I have this object

let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2' values: ['test 3', 'test 4']}
]

I want to search for values = 'test 3' and it will return objects contaning that skills ouput: {name: 'title 2' values: ['test 3', 'test 4']}

I have tried searching like obj.find(c=> c.skills), iteration etc. but it only works not inside the array of objects.

2
  • do you want an array of objects or a single object? Commented Dec 23, 2021 at 14:37
  • Is your question answered? Commented Jan 14, 2022 at 20:14

5 Answers 5

1

I'd use filer to apply a condition on values:

 let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2', values: ['test 3', 'test 4']}
];

const result = obj.filter(o => o.values.includes('test 3'));

console.log(result);

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

Comments

0

You could find the object by looking into the array with Array#includes.

const
    objects = [{ name: 'title 1', values: ['test 1', 'test 2'] }, { name: 'title 2', values: ['test 3', 'test 4'] }],
    value = 'test 3',
    result = objects.find(({ values }) => values.includes(value));

console.log(result);

1 Comment

This will only return the first match.
0

Use filter:

let obj = [{
  name: 'title 1',
  values: ['test 1', 'test 2']
}, {
  name: 'title 2',
  values: ['test 3', 'test 4']
}];

let skill = 'test 3';
let result = obj.filter(c => c.values.includes(skill));

console.log(result);

Comments

0

filter() and indexOf() should do it.

let obj = [
   {name: 'title 1', values:['test 1', 'test 2']},
   {name: 'title 2', values: ['test 3', 'test 4']}
];
    
    let ans = obj.filter(x => x.values.indexOf('test 3') > -1);
    console.log(ans);

Comments

0

filter with includes already done. find with includes already done. Then i show the forEach version today ;-)

obj = [{
  name: 'title 1',
  values: ['test 1', 'test 2']
}, {
  name: 'title 2',
  values: ['test 3', 'test 4']
}];

n = []
obj.forEach(c => {
  if (c.values.includes('test 3')) {
    n.push(c)
  }
})

console.log('new', n)

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.