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
*/
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Mar 29, 2016 at 20:38
\$\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();
answered Mar 29, 2016 at 21:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.