0

i would like to get the "-lists" data from an array with several objects:

[{...},{...},{...},{"-name": "Test", "-lists": [123, 456, 789]},{...}]

i tried with a filter function but it doesnt works :-(

this is the query where i would like to change the result to the value/array of "-lists"

             .findOne({ _id: serviceID }, function (err, result) {
                if (err) {
                    res.json(err);
                } else {
                    try{
                        res.json(result.service.modules)
                        console.log(result.service.modules)
                    }catch(error){
                        console.log(error)
                    }
                        
                }
            })

Have someone an idea for me?

Best regrads & stay healthy

2 Answers 2

1

This is an example of one of the approaches you can use to extract the value of an array nested in an object which is inside an array.

const arr = [{ someValue: 1 }, { "-lists": [1, 2, 3] }];
const result = [];

arr.filter((val) => {
  if (val["-lists"]) {
    result.push(...val["-lists"]);
  }
});

console.log(result);

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

1 Comment

no problem! make sure to mark this as an answer so it will help other people who have the same problem :)
1

You can try the map function of the array.

const data = [
  {"-name": "Test", "-lists": [123, 456, 789]},
  {"-name": "Test", "-lists": [222, 333, 444]}
 ];
 
 const result = data.map((x) => x['-lists']);
 
 console.log(result);

This will return an array of the lists data which is an array in itself.

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.