manipulate the object value without knowing its key - javascript

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);

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);

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)

Related

Nested Object Loop in JS

I'm trying to add a series of values to a nested object, having some trouble with the loop in the following code. Any help would be really appreciated.
let settings = {};
function write(id, values) {
if(!settings[id]) settings[id] = {};
for(var x = 0; x < Object.keys(values).length; x ++) {
settings[id][values[x]] = values[values[x]];
}
}
//example
write('example', {'prop1': 5, 'prop2': 10});
You're attempting to index the object values with x, which is a number. To loop through the keys of your object you can use a for...in loop:
function write(id, values) {
if(!settings[id]) settings[id] = {};
for(const key in values) {
settings[id][key] = values[key];
}
}
Another approach would be to use object destructuring:
function write(id, values) {
settings[id] = { ...(settings[id] || {}), ...values };
}
values is an object. Accessing values[x] will return undefined.
You have to access it with the correct keys in that object as below.
let settings = {};
function write(id, values) {
if (!settings[id]) settings[id] = {};
const keys = Object.keys(values);
for (var x = 0; x < keys.length; x++) {
settings[id][keys[x]] = values[keys[x]];
}
console.log(settings)
}
//example
write('example', { 'prop1': 5, 'prop2': 10 });
try to keep the Object.keys(values) return in another variable and use it to assign value in setting like this
function write(id, values) {
if(!settings[id]) settings[id] = {};
const key = Object.keys(values)
for(var x = 0; x < key.length; x ++) {
settings[id][key[x]] = values[key[x]];
}
}

Javascript building an object directly

I have these values:
let buffer = {};
let value = 'value';
let x = 1;
let y = 2;
This is what I want to do:
buffer[x][y].value = value;
This is what I need to do, in order for it to work:
buffer[x] = {};
buffer[x][y] = {};
buffer[x][y].value = value;
My guess is that there is a better, maybe built in way to create an object like this in one step instead of three.
My guess is that there is a better, maybe built in way to create an object like this in one step instead of three.
What you have is fine, but you can also do it with computed properties (I'm assuming you need the values from variables) and shorthand property notation (for value):
let value = 'value';
let x = 1;
let y = 2;
let buffer = {
[x]: {
[y]: {
value
}
}
};
console.log(buffer);
If you want to create nested object based on a set of keys, you could use reduceRight. Use the rest parameters syntax to get the value and the array of paths as separate variables. Set the value as the initialValue parameter and add a level of nesting in each iteration
const create = (value, ...paths) => paths.reduceRight((r, k) => ({ [k]: r }), value)
console.log(create("final value", "1", "2", "value"))
console.log(create("final value", "any", "number", "of", "keys"))
Like this?
const buffer = {
1: {
2: {
value: 'value'
}
}
};
If x and y are already defined, then use computed properties:
let x = 1;
let y = 2;
const buffer = {
[x]: {
[y]: {
value: 'value'
}
}
};
You could reduce the given keys and assign the value at the last step.
const
setValue = (object, path, value) =>
path.reduce((o, k, i, { length }) => o[k] = i + 1 === length
? value
: o[k] || {}, object);
let buffer = {};
let value = 'value';
let x = 1;
let y = 2;
setValue(buffer, [x, y, value], value);
console.log(buffer);

Javascript - Get the associative array key value

I have an object with one key value as given below -
var a = {};
a.x = "randomvalue";
My requirement is to get access the value "randomvalue", but the catch is I dont know that the property name is "x".
Simplest way to get the value??
Try:
var v, i;
var a = {};
a.x = "randomvalue";
for (x in a) {
if a[x] === "randomvalue" {
v = x;
i = "randomvalue";
}
}
Then v contains the object key and i contains the object value (although you don't really need it).
Or, if you know the value index:
var obj = { first: 'someVal' };
obj[Object.keys(obj)[0]]; //returns 'someVal'

Returning key/value pair in javascript

I am writing a javascript program, whhich requires to store the original value of array of numbers and the doubled values in a key/value pair. I am beginner in javascript. Here is the program:
var Num=[2,10,30,50,100];
var obj = {};
function my_arr(N)
{
original_num = N
return original_num;
}
function doubling(N_doubled)
{
doubled_number = my_arr(N_doubled);
return doubled_number * 2;
}
for(var i=0; i< Num.length; i++)
{
var original_value = my_arr(Num[i]);
console.log(original_value);
var doubled_value = doubling(Num[i]);
obj = {original_value : doubled_value};
console.log(obj);
}
The program reads the content of an array in a function, then, in another function, doubles the value.
My program produces the following output:
2
{ original_value: 4 }
10
{ original_value: 20 }
30
{ original_value: 60 }
50
{ original_value: 100 }
100
{ original_value: 200 }
The output which I am looking for is like this:
{2:4, 10:20,30:60,50:100, 100:200}
What's the mistake I am doing?
Thanks.
Your goal is to enrich the obj map with new properties in order to get {2:4, 10:20,30:60,50:100, 100:200}. But instead of doing that you're replacing the value of the obj variable with an object having only one property.
Change
obj = {original_value : doubled_value};
to
obj[original_value] = doubled_value;
And then, at the end of the loop, just log
console.log(obj);
Here's the complete loop code :
for(var i=0; i< Num.length; i++) {
var original_value = my_arr(Num[i]);
var doubled_value = doubling(original_value);
obj[original_value] = doubled_value;
}
console.log(obj);
You can't use an expression as a label in an Object literal, it doesn't get evaluated. Instead, switch to bracket notation.
var original_value = my_arr(Num[i]),
doubled_value = doubling(Num[i]);
obj = {}; // remove this line if you don't want object to be reset each iteration
obj[original_value] = doubled_value;
Or:
//Original array
var Num=[2,10,30,50,100];
//Object with original array keys with key double values
var obj = myFunc(Num);
//Print object
console.log(obj);
function myFunc(arr)
{
var obj = {};
for (var i in arr) obj[arr[i]] = arr[i] * 2;
return obj;
}

How to build nested properties from key strings

var keys1 = ["foo", "moreFoo"],
value1 = "bar",
keys2 = ["foo", "ultraFoo"],
value2 = "bigBar";
I'd like to make a function which would build me an object :
object {
foo : {moreFoo: "bar", ultraFoo: "bigBar"}
}
I thought of taking each one of my arrays and doing the following :
function recursiveObjectBuild(object, keys, value) {
var index = 0;
function loop(object, index) {
var key = keys[index];
//Property exists, go into it
if (key in object) {
loop(object[key], ++index);
//Property doesn't exist, create it and go into it
} else if (index < keys.length-1) {
object[key] = {};
loop(object[key], ++index);
//At last key, set value
} else {
object[key] = value;
return object;
}
}
return loop(object, 0);
}
Which should work IMO but doesn't (infinite loop, must be a stupid mistake but can't see it).
And I'm sure there must be a much simpler way
Try the following:
function objectBuild(object, keys, value) {
for (var i = 0; i < keys.length-1; i++) {
if (!object.hasOwnProperty(keys[i]))
object[keys[i]] = {};
object = object[keys[i]];
}
object[keys[keys.length-1]] = value;
}
Example usage (see it in action):
var object = {};
objectBuild(object, ["foo", "moreFoo"], "bar");
objectBuild(object, ["foo", "ultraFoo"], "bigBar");
// object --> {foo: {moreFoo: "bar", ultraFoo: "bigBar}}

Categories

Resources