Olli Olli - 1 month ago 9
Javascript Question

Get key/value from object, perform function and send back in

I am getting

[{id:'test', time: '1223'}, {id: 'test2', time: '2323'}]
from the backend, I need to retrieve the time values for all, perform a function and send back into the object as
[{id:'test', time: 'new value for test'}, {id: 'test2', time: 'new value for test2'}]


So I decided I would try and extract the time values and push into array using
for loop
but my
for loop
is missing something

var objext = [{id:'test', time: 'blah'}, {id: 'test2', time: 'blah'}];
var dataArray = new Array;
for (var id in objext) {
dataArray.push(objext[id]);
};


It returns the same obviously as I don't know how to select the
time
key.

And then I'll run my function for each as such which is working well:

var time = [23,34,56];
var map = time.map(function(num) {
if (num === 23) {
return num +2;
} else {
return num;
};
});


And then the final part will be to put back and I'm thinking I could get an array of
id
and one of
time
and then slot back in together but the code I have so far can only map one array at a time:

var data = ["Drake","Ola","d"],
result = data.map(function (a) { return { id: a }; });


I have tried using an array as such:

var data = ["Drake","Ola","d"];
var hht = [21,34,56];
result = [data,hht].map(function (a,b) { return { id: a, time:b }; });


It did not map it properly.
Any ideas?

Answer

You can perform all of the tasks withing .map() callback

var objtext = [{id:'test', time: '1223'}, {id: 'test2', time: '2323'}];
objtext = objtext.map(function(obj) {
  var time = obj.time; 
  // do stuff with `obj.time`
  if (time == 1223) {
    time += 2;
    obj.time = time;
  }
  if (time == 2323) {
    time -= 2;
    obj.time = time;
  }
  return obj
});

To create an array containing only time properties

var times = objtext.map(function({time}) {return time});