Oam Psy
Oam Psy

Reputation: 8663

Lodash searching object properties and modifying value

I am trying to loop through an object, looking for values defined in an array. The properties are typically ones with a epoch timestamp.

Once a property is found, I want to convert that properties' value to human readable.

may myArray = ["dob", "movingDate"];

var myObj = {
    prop1: "hi",
    prop2: "goodnight",
    prop3: "welcome",
    prop4: "now",
    name: "Alfred",
    age: 46,
    dob: 3165300688,
    gender: "female",
    movingDate: 1461233587
}

for (var i = 0; i < myArray.length; i++) {    
    var exists = _.has(myObj, myArray[i]);
}

Which correctly finds the properties if present, but how can I get the properties value?

I can fix the above using standard Object.Keys notation, but I am trying to do this with lodash and moment.

Once I have the property, I can use moment to convert via:

prop = moment.format('DD-MM-YY HH:mm:ss.SSS');

Should I be using:

_.pick

Or:

_.update

Upvotes: 2

Views: 3888

Answers (3)

Adam Boduch
Adam Boduch

Reputation: 11211

You could do something like this:

function formatDate(val) { return new Date(val); }

_.assign({}, myObj,
  _(myObj)
    .pick(myArray)
    .mapValues(formatDate)
    .value());

Note, that the call to assign() will actually create a new object instead of mutating myObj. This is because of the first argument - {}. If you need to modify the myObj reference, just remove this first argument.

The value that gets assigned is the result of picking values based on myArray and pick(). Since this returns an object, we want to use the mapValues() function for format the dates - the formatDate() function can return anything.

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

You can get the property value by simply doing

myArray.forEach(function(val){
  if ( myObj.hasOwnProperty(val) )
  {
    myObj[val] = formatDate(myObj[val]);
  }
});

Assuming that you have a method formatDate to format timestamp to date format using moment (or any of your fav library)

Upvotes: 1

dfsq
dfsq

Reputation: 193261

You don't even need lodash here, simple forEach with in-operator to test for property presence could be enough:

myArray.forEach(function(value) {
  if (value in myObj) {
    myObj[value] = moment.unix(myObj[value]).format('DD-MM-YY HH:mm:ss.SSS');
  }
});

Upvotes: 0

Related Questions