0

I have a complex nested array of objects like this for which I have to return a new Array(filter) based on attributeScore > 90. How will I accomplish this using the javascript .filter or the lodash _.find() or _.some function ?

trucks:[
     {wheels:[
             {name:"xyz",
              mechanics: [
                     {engine:'50cc',
                     attributeScore:100},
                     {....} ,{...}
                    ]
              },
              {name:"gcd",
              mechanics: [
                     {engine:'80cc',
                     attributeScore:90},
                     {....} ,{...}
                    ]
              }, 
            ,{...}
         ]}
         ,{...}
      ]

I tried a filter like this

const fil = trucks.filter(function(item) {
    return item.wheels.some(function(tag) {
      return tag.mechanics.some(function(ques){
        return ques.attributeScore <= 25;
      });
    });
  });

but it returns an empty array . My expected return array type should be

trucks:[
     {wheels:[
             {name:"xyz",
              mechanics: [
                     {engine:'50cc',
                     attributeScore:100},
                     {....} ,{...}
                    ]
              },
            ,{...}
         ]}
      ]

Any help appreciated!!

2
  • You must be clearer. What exactly will you filter? Can you post an example of what you'd get after filtering this example? Commented Mar 21, 2018 at 9:12
  • @OscarPaz . Sorry updated the question now Commented Mar 21, 2018 at 9:18

2 Answers 2

2

Try this now,

var fill = trucks.map(function(item) {
    return item.wheels.map(function(tag) {
      return tag.mechanics.filter(function(ques){
        return ques.attributeScore == 100;
      });
    });
  });
Sign up to request clarification or add additional context in comments.

4 Comments

I need all the contents of the array after the filter is applied , but this chops the parent objects and returns only the child
Yes. Parents are object. So we can't slice the object in filter. Its only for array
Meaning this only returns the child array !! Not the nesting
According to your structure it will return only child
2

If I understand what you are asking, I think this function should do the trick:

_.map(trucks, truck => ({ 
  ...truck,
  wheels: _.filter(_.map(truck.wheels, wheel => ({
    ...wheel,
    mechanics: _.filter(wheel.mechanics, m => m.attributeScore > 90)
  })), wheel => wheel.mechanics.length),
}));

It's not a terribly elegant solution, but I wind up with the same answer as you were hoping for in your original post.

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.