1

I have an array:

var array1 = [{ make: "John Deere", model: "4030", time:"-KzbzyNy-nh1E3wQY7uz", uid:0, year:"1952" }]

I want to grab the "time" value and set it to the "uid" value. So, it would become:

var array1 = [{ make: "John Deere", model: "4030", time:"-KzbzyNy-nh1E3wQY7uz", uid:"-KzbzyNy-nh1E3wQY7uz", year:"1952" }]

It's totally fine if "-KzbzyNy-nh1E3wQY7uz" is repeated because it's set to two different keys.

How would I go about this? I'm new to javascript., so sorry if this is too basic of a question.

Jared Nelson
  • 254
  • 4
  • 13

4 Answers4

0

try this one

var array1 = [{
  make: "John Deere",
  model: "4030",
  time: "-KzbzyNy-nh1E3wQY7uz",
  uid: 0,
  year: "1952"
}];

//set it manually using key of array
array1[0]['uid'] = array1[0]['time'];

console.log(array1);
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
0

Loop over array and make a simple assignment for each object by passing the value of time to the property uid

var array1 = [{
  make: "John Deere",
  model: "4030",
  time: "-KzbzyNy-nh1E3wQY7uz",
  uid: 0,
  year: "1952"
}];
// o is current array element which is an object
array1.forEach(o => o.uid = o.time);

console.log(array1);
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

This solution will work for an array of any length. Some of the other solutions will only work if the array is of length 1 and the object you want to modify will always be in the array.

This solution will work for an array (of similar objects) of any length.

for(var i = 0; i < array1.length; i++) {
   var current = array1[i];
   current.uid = current.time;
}
pidizzle
  • 720
  • 6
  • 12
0

I wish I could choose more answers than just one. All of these work, I didn't know it was as easy as assigning one value to the next. Here's my final code:

 const array2 = [];

 array1[0].uid = array1[0].time;

 const len = array1.length;

 for (let i = 0; i < len4; i++) {
 array2.push(array1);
 }

   console.log(array2);

I probably don't need array2 in there at all, but just added that other step.

Jared Nelson
  • 254
  • 4
  • 13
  • That would push the whole array1 each time and you would end up with an array of arrays each being the same. Highly doubt that is what you want – charlietfl Nov 24 '17 at 05:22
  • You're right, it totally made an array of arrays. Had to write this instead: var array2 = array1[i]; Thanks for your help! – Jared Nelson Nov 25 '17 at 06:39