Hello guys I'm trying to get each element of an array as the property values of some objects. Therefore I was using a function but it's not dynamic at all because I need to always specify the index of the array after calling the function.
This is my code:
function grab(){
var arr= [123456,987654]
return arr
}
var arrayObjects= [
{title: "miami", hash: grab()[0]},
{title: "new york", hash: grab()[1]}
]
console.log(arrayObjects[0].hash)
What's another more efficient approach?
3 Answers 3
Try like this.Directly Pass the value with in a function
function grab(n) {
return [123456, 987654][n];
}
var arrayObjects = [{ title: "miami" }, { title: "new york"}]
arrayObjects.forEach((a,b)=> a['hash'] = grab(b));
console.log(arrayObjects[0].hash)
1 Comment
Maybe this ?
function grab() {
var arr = [123456, 987654];
return arr;
}
var hashes = grab();
var arrayObjects = [{title: "miami"}, {title: "new york" }];
arrayObjects.forEach((item, index) => item.hash = hashes[index]);
console.log(arrayObjects[0].hash);
This is a simple snippet. An index validation could be helpful to avoid out of range exceptions when trying to access hashes array inside the forEach loop. But is just an example.
2 Comments
function grab() { return [123456, 987654]; }. Or ditch the function altogether.If you are worried about indexes, you may wish to turn arr variable into an object with some sort of id specified, and call your hases using this id. For example:
function grab(){
var hashes = {
'miami': 123456,
'ny': 987654
};
return hashes;
}
var arrayObjects= [{title: "miami", hash: grab().miami}, {title: "new york", hash: grab().ny}]
grabas a function? Why don't you just declare the array where you need it?