0

I have an object test, with fields a and b that have nested properties say:

test = {a: {key1: 'value1', key2: 'value2', key3: 'value3'},
       {b: {key1: 'value4', key2: 'value5', key3: 'value6'}}

I want to be able to change the nested values inside either a or b, but have the one I'm changing be variable. For clarity, I want to be able to do something like:

test.$i$.key1: 'value10'

where $i$ refers to the value that i holds, in this case either a or b.

Is that possible?

I am aware that this is easily solved with bracket notation, but this will not work in my situation.

Copied from firebase docs:

// Create an initial document to update.
var frankDocRef = db.collection("users").doc("frank");
frankDocRef.set({
    name: "Frank",
    favorites: { food: "Pizza", color: "Blue", subject: "recess" },
    age: 12
});

// To update age and favorite color:
db.collection("users").doc("frank").update({
    "age": 13,
    "favorites.color": "Red"
})
.then(function() {
    console.log("Document successfully updated!");
});

I want to be able to do:

const var1 = 'color'
db.collection("users").doc("frank").update({
    "age": 13,
    "favorites.$var1$": "Red"
})

where $var1$ refers to the value that $va1r$ holds, in this case either food, color or subject.

Bracket notation does not work in this case, as I am passing a string to firebase, which it doesn't interpret like that.

CEH
  • 5,701
  • 2
  • 16
  • 40
Joram
  • 125
  • 2
  • 13

2 Answers2

2

You can access property of an object dynamically using Bracket notation.

Try the below code:

var test = {
  a: {
    key1: 'value1',
    key2: 'value2',
    key3: 'value3'
  },
  b: {
    key1: 'value4',
    key2: 'value5',
    key3: 'value6'
  }
};

var key = 'a';
console.log(test[key].key1);
1

Either use a computed property:

const var1 = 'color'
db.collection("users").doc("frank").update({
    "age": 13,
    ["favorites." + var1]: "Red"
})

Or construct the object "outside" of the update call:

const var1 = 'color'

const data = { "age": 13 };
data["favorites." + var1] = "Red";

db.collection("users").doc("frank").update(data)
Andreas
  • 21,535
  • 7
  • 47
  • 56