'How to assign key to each Item or value in array in javascript?

I have an array like this:

[link1,link2,link3]

But I want it like this:

[uri:link1,uri:link2,uri:link3]

Please guide me over this. Thanks.



Solution 1:[1]

maybe you could try by mapping your array and returning new array of object like this

const array1 = [1, 2, 3, 4];
const newArr = array1.map(i => {return {uri: i}})

console.log(newArr);
// > Array [Object { uri: 1 }, Object { uri: 2 }, Object { uri: 3 }, Object { uri: 4 }]

Solution 2:[2]

If you need in the form of (Array of objects)

var test = ['a', 'b', 'c', 'd'];

function setID(item, index) {
  var fullname = {"id: ": item};
  return fullname;
}

var output = test.map(setID);
console.log(output);

output: [ { "id: ": "a" }, { "id: ": "b" }, { "id: ": "c" }, { "id: ": "d" } ]

Solution 3:[3]

Use Array.from! It's really simple and faster.

var test = ['a', 'b', 'c', 'd'];
var newTest = Array.from(test, val => 'id: '+ val);
console.log(newTest);

output: [ "id: a", "id: b", "id: c", "id: d" ]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 petrov
Solution 2
Solution 3 Dinesh Vishwakarma