7

I'm trying to select only certain values from my object to write into a file. But this writes the whole object and also unless I use util.inspect it just writes as objects. This should write the values I have chosen from the objects line by line as they come in:

var objectsToFile = function(objectsTotal){

    objectsTotal = _.values(objectsTotal, function(value) {
        return value.objectTo.employeeName;
    });

    objectsTotal = _.values(objectsTotal, function(value) {
        return value.employeeCurrent;
    });

    objectsTotal = _.values(objectsTotal, function(value) {
        return value.employeePast;
    });



        writeFile('objectsTotalet.csv', util.inspect(objectsTotal), function(err) {
            if (err) console.log(err);
        });
};

objectsTotal comes through the function like:

[ { objectTo:                        
 { employeeName: 'John',         
   employeeID: '234234', 
   DOB: '2333'},         
employeeCurrent: true,
employeePast: false},  
{ objectTo:                        
 { employeeName: 'Janet',         
   employeeID: '23423432', 
   DOB: '23333' },        
employeeCurrent:true,
employeePast: false} ]

The output will be conditional which is why I'm using the underscore library but it doesn't work it doesn't even use the returned values from underscore:

There will be other values added to the object so will also need to add a return value like:

objectsTotal = _.values(objectsTotal, function(value) {
        return value.employeeStatus != 'employed' ||
        value.url.indexOf('employee:') === -1 ||
        value.employeeid.length === ('id:')
});

I do need to use this library to give the results I want in a csv file. The output will look like the objectsTotal values returned line by line and can be in one cell.

2
  • Why do you insist on using underscore?
    – cнŝdk
    Commented Nov 6, 2017 at 14:22
  • @chsdk The code is already written in my other application that doesn't use node, if you can provide an answer that works the same way with the last condition too I will use it.
    – Sam
    Commented Nov 6, 2017 at 14:39

2 Answers 2

2
+150

Well your underscore code doesn't seem to work because it doesn't return any result in your _.values() calls.

I think you are mis-using the _.values() method from the _.values() underscore Docs we can see that it doesn't have a second argument for a callback, so I think the code in this callback will never be executed.

Solution:

Anyway this can be achieved with pure JavaScript code:

var filteredObjects = objectsTotal.filter(function(value) {
  return value.objectTo.employeeStatus != 'employed';
}).map(function(obj) {
  return {
    employeeName: obj.objectTo.employeeName,
    employeeCurrent: obj.employeeCurrent,
    employeePast: obj.employeePast
  }
}).map(function(o) {
  return Object.values(o);
});

Explanation:

  • We use .filter() method to filter the objects having the specified conditions, I used only one test but you can implement all your tests, it will give us an array with all the objects matching these conditions.
  • Then we use .map() method to get only employeeName, employeeCurrent and employeePast properties of each object.
  • Then we recall .map() to get only the values of these propeties using Object.values() in the callback function.

After filtering your array of objects, you can transform it to a string using .reduce() method like this:

var filteredResult = filteredObjects.reduce(function(acc, currentValue) {
    return accumulator + currentValue.join(" \n");
}).join(" ,");

Then write the content of filteredResult string variable to your csv file:

writeFile('objectsTotalet.csv', filteredResult, function(err) {
    if (err) console.log(err);
});

Demo:

var objectsTotal = [{
    objectTo: {
      employeeName: 'John',
      employeeID: '234234',
      DOB: '2333',
      employeeStatus: 'employed'
    },
    employeeCurrent: true,
    employeePast: false
  },
  {
    objectTo: {
      employeeName: 'Janet',
      employeeID: '23423432',
      DOB: '23333',
      employeeStatus: 'unemployed'
    },
    employeeCurrent: true,
    employeePast: false

  }
];

var filteredObjects = objectsTotal.filter(function(value) {
  return value.objectTo.employeeStatus != 'employed';
}).map(function(obj) {
  return {
    employeeName: obj.objectTo.employeeName,
    employeeCurrent: obj.employeeCurrent,
    employeePast: obj.employeePast
  }
}).map(function(o) {
  return Object.values(o);
});

var filteredResult = filteredObjects.reduce(function(acc, currentValue) {
    return accumulator + currentValue.join(" \n");
}).join(" ,");

console.log(filteredResult);
<script src="http://underscorejs.org/underscore-min.js"></script>
<script data-require="lodash.js@*" data-semver="4.17.4" src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

7
  • Thanks for this how would you create and write to the file and also do you have any idea why my code isn't working? Also there will be a lot of objects coming through and each set needs to be on a new line sorry.
    – Sam
    Commented Nov 6, 2017 at 15:47
  • @Sam your code doesn't return anything, I think the problem comes from the conditions you are using for example the last one value.employeeid.length === ('id:') will be always false because you are trying to compare a string to a number.
    – cнŝdk
    Commented Nov 6, 2017 at 15:55
  • This works, thanks alot. Only one problem left it's including the brackets [[ and also the quotes ', how can I get rid of these? With my code even in the first return statement if I do a console.log this never gets printed do you know why?
    – Sam
    Commented Nov 6, 2017 at 15:57
  • @Sam I think you are mis-using the _.values()method from the ._values() underscore Docs we can see that it doesn't have a second argument for a callback, so I think the code in this callback will never be executed.
    – cнŝdk
    Commented Nov 6, 2017 at 16:02
  • @Sam I edited the answer to make it write the results as a string, ommitting the double [[]].
    – cнŝdk
    Commented Nov 6, 2017 at 16:12
1

Well, I realized what you want to achieve in a plunker using lodash with a chain of multiple functions, this is the code used :

// First, do your filtering conditions here
var game = data.filter(g => {
   return g.debit === true; 
});

// Then, pick the wanted attributes here
game = _.map(game, (g) => {
    var o = _.pick(g, ['amount', 'debit']);
    o = Object.values(o);
    return o;
});

// Finally merge your arrays here
var merged = [].concat.apply([], game);

For printing your array into csv, you just have to use the final merge array in your printing function.

Here's the plunker link: http://plnkr.co/edit/uvH4Ww4HMaQQVXQCBVKP

I hope that I answered your question as needed.

PS: I can explain every block of code which isn't clear.

3
  • But how would I achieve the last condition where I return based on OR conditions. I would just like to know why the code above isn't working correctly. It works correctly if I don't use node in my other application so I know it is achievable
    – Sam
    Commented Nov 6, 2017 at 14:37
  • You should make your conditions in the first filter function. Commented Nov 6, 2017 at 14:48
  • Okay thanks can you replace the variables with what I have used and return the same output, I'm giving 150 points and need to see if your code will work :)? And explain why it doesnt work the way I have done it, it doesn't even get into the _ functions.
    – Sam
    Commented Nov 6, 2017 at 14:55

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.