Access object property via list of strings in javascript [duplicate] - javascript

This question already has an answer here:
Index an array of arrays with an array of indexes in javascript
(1 answer)
Closed 2 years ago.
If I have an array describing the path to an object property, e.g ['user', 'personal_info', 'age] and I want to set an object's property according to it, say myObject.user.personal_info.age = 30, how would I do that?

Loop through the keys in the array and use them to access the object properties as though it were a dictionary. (Skip the last key because you need it to access the final property.)
function updatePersonAge(person) {
let keys = ['user', 'personal_info', 'age'];
let obj = person;
for (let i = 0; i < keys.length - 1; i++) {
obj = obj[keys[i]]; // user, personal_info
}
obj[keys[keys.length - 1]] = 30; // age
}
let person = { user: { personal_info: { age: 10 }}};
updatePersonAge(person);
console.log(person);

Related

Make key value pair from two different array [duplicate]

This question already has answers here:
Merge keys array and values array into an object in JavaScript
(14 answers)
Closed 1 year ago.
I'm using local storage to get an arrays of strings,
First value attrIds is as follows,
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
Second value confOptions is as follows,
I want something like this,
144: "5595"
93: "5487"
I have tried creating a loop inside the loop and tried to set the key and value but it's not working. I have also tried to set the single JSON object as key and setting value as '' but couldn't move further with that.
Does anyone have any idea regarding this?
You can accomplish this using a simple for loop, accessing the items from the arrays, and assigning properties to an empty object.
const keys = ['144', '93'];
const values = ['5595', '5487'];
const obj = {};
for (let i = 0; i < keys.length; i++) {
obj[keys[i]] = values[i];
}
console.log(obj); // prints { 144: '5595', 93: '5487' }
Create a nested array and then use Object.fromEntries().
const
a = ["144", "93"],
b = ["5595", "5487"],
c = Object.fromEntries(a.map((v, i) => [v, b[i]]));
console.log(c);
Using a for loop, you could do something like:
var attrIds = localStorage.getItem('attributeids');
attrIds = JSON.parse(attrIds);
confOptions = ["5595", "5487"]
const object = {};
for(let i=0; i<attrIds.length;i++)
object[attrIds[i]] = confOptions[i]

Javascript Grammer: how to assign correct values to an array of objects [duplicate]

This question already has answers here:
new Array(_).fill(object) does not create new instances of object [duplicate]
(5 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Closed 2 years ago.
let's look at the code:
Test() {
let array1 = new Array(5).fill({ a: 0 })
let array2 = new Array(5).fill({ a: 0 })
for (let i = 0; i < 5; i++) {
setTimeout(() => {
array1[i].a = i
array2[i] = {a:i}
console.warn("array = ", array1)
console.warn("array2 = ", array2)
}, 0.2 * i)
}
}
In this case, I wanna assign a series of values to the array1 & array2, and there are two ways to do it, which lead to totally different results.
In the case array1[i].a = i, after all the code is ran, the result is array = [{a:4},{a:4},{a:4},{a:4},{a:4}], which is not what i wanted.
In the second case array2[i] = {a:i}, the result will be [{a:0},{a:1},{a:2},{a:3},{a:4}] as expected.
I wanna know why is it like this? What's the machanics behind this phenomenon?
Thank you.
When you call .fill() and pass an object, you assign the exact same object to every element of the array. Thus, modifying a property at one array index modifies the same property at all the other indexes, because they're all pointing to the same thing.
There are a variety of ways around this issue. You could fill the array with 0 or null or some dummy value and then iterate through with .forEach(), or more simply just use an indexed for loop to initialize each element. If you initialize with { a: 0} in a for loop, a new object will be created on each iteration.

JavaScript scope: preserve object in array in function [duplicate]

This question already has answers here:
How to copy JavaScript object to new variable NOT by reference? [duplicate]
(2 answers)
Closed 3 years ago.
I am using .map() on an array inside a function. I am not modifying the array itself (arr = arr.map(...)), but rather creating a new array (var arr2 = arr.map(...)).
Yet, this still modifies the original arr outside my function (which I don't want). How can I preserve?
var arr = [{prop: 1}];
myFunction(arr);
console.log(arr[0].prop); // returns 2, I want it to return 1
function myFunction(arr) {
var arr2 = arr.map(obj => {
obj.prop = 2;
return obj;
});
console.log(arr[0].prop); // returns 2
}
It modifies based on its reference. If you want to create a new object and modify its properties then you need to use Spread Syntax. Read the documentation:
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected, or an object
expression to be expanded in places where zero or more key-value pairs
(for object literals) are expected.
You can try the following:
var arr = [{prop: 1}];
myFunction(arr);
function myFunction(arr) {
var arr2 = arr.map(obj => {
let copyObj = {...obj};
copyObj.prop = 2;
return copyObj;
});
console.log(arr[0].prop);
console.log(arr2[0].prop);
}

Loop through JavaScript object and return new object with modified value [duplicate]

This question already has answers here:
How to iterate over a JavaScript object?
(19 answers)
Closed 3 years ago.
I have an object which I am forming with all the input values from a form. I want to go through the object and change all the input value to lowercase before I make a post request to the backend. I want to write a function that takes that object and returns a new object with lowercase value
const obj = {name: 'Test', city: 'London'}
const modifiedObj = myFunction(obj)
modifiedObj should be:
{name: 'test', city: 'london'}
You can use Object.keys to get the keys of your object, then iterate through them and access each property.
function myFunction(object){
const newObj = {};
cons keys = Object.keys(object);
for(const key of keys){
if(typeof object[key]!=="string"){
newObject[key] = object[key];
continue;
}
newObj[key] = object[key].toLowerCase();
}
return newObj;
}

Javascript Object order incorrect [duplicate]

This question already has answers here:
How to keep an Javascript object/array ordered while also maintaining key lookups?
(2 answers)
Closed 7 years ago.
I have got a function which retrieves an object.
This object has a property and a value. The property is numeric and starts at "-30" all the way up to "50"
The problem is that when I loop through this object the browser seems to order it starting at "0" instead of starting at the initial property of "-30"
I need to make sure the order is exactly the same as the object.
var colorOj = {
"-30":"#111","-29":"#131313", ..etc.., "0":"#333", ..etc..,
"50":"#555"
}
function makeList(object){
for (var i in object) {
console.log(i); // Returns 0,1,2,3,4,5
// I need a return of -30,-29,-28,..., 0, 1, 2 ...
}
}
makeList(colorObj);
As suggested by #Teemu, properties are not stored in any specific order. But you can print them in any order using specific sort function accordingly.
Code
var obj = {};
for (var i = 5; i > -5; i--) {
obj[i * 10] = i * 10;
}
// Sort and get all keys...
var keys = Object.keys(obj).sort(function(a, b) {
return parseInt(a) - parseInt(b);
});
console.log(keys)
// Loop over keys to print values of each property
keys.forEach(function(item) {
console.log(item, obj[item]);
})
You can do something like this maybe:
var colorOj = {
"-30":"#111","-29":"#131313", "0":"#333",
"50":"#555"
};
var keys = Object.keys(colorOj).sort(function(a,b){return a - b})
for(var i = 0; i < keys.length;i++){console.log(keys[i])}
This way you can get every key in the object. Then sort it however you like(the sort function in javascript can take a compare function as a parameter look -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

Categories

Resources