Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 984
Olli Avatar asked Dec 08 '25 16:12

Olli


2 Answers

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});
like image 84
guest271314 Avatar answered Dec 10 '25 06:12

guest271314


You could use an array, iterate it and use from the other parts as well for a new object.

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

console.log(result);
like image 20
Nina Scholz Avatar answered Dec 10 '25 04:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!