It seems like you're unsure about the desired functionality of your code, so I'll make some assumptions based on what you've provided.
Let's analyze the code snippet from your question:
var array = [{someValue: 5}, {someOtherValue: 10}];
var newArray = [];
var obj = {value: "someValue"};
var setValue = function(choosenValue) {
for (let i = 0; i < array.length; i++) {
newArray.push({
choosenValue: array[i].choosenValue
});
}
}
setValue(obj.value);
From this code, it appears that you want to populate the newArray
with values based on the 'choosenValue' property in the objects stored in the 'array'. However, the logic you're trying to implement is more suited for a Map or Dictionary data structure rather than an Array.
Instead of using an array like
var array = [{someValue: 5}, {someOtherValue: 10}]
You could utilize a map like
var map = { someValue: 5, someOtherValue: 10 }
This way, you can directly access values by keys such as map.someValue
or map[choosenValue]
.
The current loop in your code attempts to retrieve the 'choosenValue' property from each object in the array. However, since the objects in the array have different property names ('someValue', 'someOtherValue'), accessing 'choosenValue' will result in 'undefined' values.
If you intend to extract values based on specific properties, you should revise the loop to something like:
var array = [{ someValue: 5, someOtherValue: 10 },
{ someValue: 6, someOtherValue: 12 }];
var newArray = [];
var setValue = function(choosenValue) {
for (let i = 0; i < array.length; i++) {
newArray.push(array[i][choosenValue]);
}
}
Now, each iteration retrieves the value specified by 'choosenValue' from the objects in the array.
If your goal is to create new objects containing the specified field name along with its value, you need to construct the object first and then set the field using bracket notation:
for (let i = 0; i < array.length; i++) {
var temp = {};
temp[choosenValue] = array[i][choosenValue];
newArray.push(temp);
}
While not the most elegant solution, this approach achieves the desired outcome.
1 - In situations where an object only holds one field and you plan to access that field individually, it may be preferable to extract the field directly instead of retaining it within an enclosing object. Encapsulation is beneficial when passing the entire object or planning future expansions.