Adarsh
Adarsh

Reputation: 524

manipulate the object value without knowing its key

I have an object obj and I want to manipulate it's value, but I don't want to write the value hard-coded something like below, is there any better alternative to this below approach

let obj = {a:{x:0}, b:{y:0}};

obj.a[Object.keys(obj.a)[0]] = 1;

console.log(obj);

Upvotes: 0

Views: 332

Answers (2)

Jasdeep Singh
Jasdeep Singh

Reputation: 8321

I have created a generic function where you can set the value of key without knowing the property names of inside object.

You can call the function with required key and value and get the desired result.

let obj = {a:{x:0}, b:{y:0}};

function assignValue(key, value) {
	obj[key][Object.keys(obj[key])] = value;
}

assignValue('a', 1)

console.log(obj)

let objMultipleInnerKeys = {a:{x:0, z:2}, b:{y:0}};

function assignValueMultipleInnerKeys(key, innerKey, value) {
	objMultipleInnerKeys[key][innerKey] = value;
}

assignValueMultipleInnerKeys('a', 'x', 1)

console.log(objMultipleInnerKeys)

Upvotes: 1

EugenSunic
EugenSunic

Reputation: 13723

I suppose you want to loop through them and have different values for x, y or whatever the key is

let obj = {
  a: {
    x: 0
  },
  b: {
    y: 0
  }
};



keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
  key2 = Object.keys(obj[keys[i]])[0];
  // instead of some_value inject an array of values 
  obj[keys[i]][key2] = 'some_value';
}

console.log(obj);

Upvotes: 1

Related Questions