0

I get the following data from an API:

[
    { names: { name: 'Pete', name;'Claus' } },
    { names: { name: 'Paul', name;'Claus' } },
    { ... }
] 

How can I get an array containing only those objects that have the name Claus in them with reduce,filter, map and such methods?

This does it - but not in a functional style though:

var newMap = []
var map = this.array
for(var i = 0; i < map.length; i++) {
  for(var j = 0; j < map.length; j++) {
    if(map[i] && map[i].involvements[j])
      if(map[i].involvements[j].full_name === 'Claus') {
        newMap.push(map[i])
    }
  }
}
this.array = newMap 

Some bits not very much though:

 search(){
    let map = this.submissions
    .map( (x,i) => x.involvements.filter(x => x.full_name === 'Claus'))
    .filter( x => x.length != 0 )
    console.log(map)
  }
4
  • 2
    That's an invalid json because has repeated keys. Commented Feb 21, 2018 at 11:19
  • Yeah, well thats what the API looks like. Commented Feb 21, 2018 at 11:20
  • 1
    Be sure about the JSON you're receiving because you won't be able to solve your problem with that invalid JSON. Commented Feb 21, 2018 at 11:23
  • Please share the correct array. Commented Mar 5, 2018 at 10:34

1 Answer 1

1

Data Structure

Based on your code, you have the following data structure:

[
  {
    involvements: [
      { full_name: 'Claus' },
      { full_name: 'Peter Paker' }
    ]
  },
  // more involvements
]

Code

What you want to do is to filter if some involvement contains an object with the property full_name. Coincidentally there are the functions Array#filter and Array#some.

const search = (x, xss) =>
    xss.filter(xs => xs['involvements'].some(y => y['full_name'] === x))

search('Claus', data) 

Working Code Example

const data = [{
    involvements: [{
        full_name: 'Claus'
      },
      {
        full_name: 'Peter Parker'
      }
    ]
  },
  {
    involvements: [{
        full_name: 'Clark Kent'
      },
      {
        full_name: 'Kristin Wells'
      }
    ]
  }
]

const search = (x, xss) =>
  xss.filter(xs => xs['involvements'].some(y => y['full_name'] === x))

console.log(
  search('Claus', data)
)

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

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.