2
\$\begingroup\$

I have the following structure returned from MongoDB:

[Class]
    0:Class // -> this.data.userInfo as seen below in the code
        _id: "ksihHTAjdhsA9"
        createdAt:Tue Mar 29 2016 13:03:45 GMT-0400 (EDT)
        weightData: Array[3]
            0: Class
                name: "my name 1"
                value: "myval1"
                weight: 154
            1: Class
                name: "my name 2"
                value: "myval2"
                weight: 191
            2: Class
                name: "my name 3"
                value: "myval3"
                weight: 210

I need to loop through the weightData nested array and store the name and value in a dictionary variable to be used in a dropdown later. I have it working, however, I feel like this could be more efficient.

var dict = [];
_.each(this.data.userInfo, info => {
  if (info) {
    _.each(info.weightData, weightInfo => {
      dict.push({
          "name": weightInfo.name, 
          "value": weightInfo.value,
          "weight": weightInfo.weight
      });
    });
  }
});

console.log(dict);

/*
[Object, Object, Object]
    0:Object
        name: "my name 1"
        value: "myval1"
        weight: 154
    1:Object
        name: "my name 2"
        value: "myval2"
        weight: 191
    2:Object
        name: "my name 3"
        value: "myval3"
        weight: 210
*/
\$\endgroup\$

1 Answer 1

-1
\$\begingroup\$

It looks like you are basically doing a filter + flatMap. You can also use destructing:

var dict = _(this.data.userinfo).filter(Boolean).flatMap(info => {
  return info.weightdata.map(({name, value, weight}) => {
    return {name, value, weight};
  });
}).value();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.