ymdahi
ymdahi

Reputation: 175

add nested values to associative array - JS

Simply stuck with this one, any help would be appreciated.

I have an associative array like this:

var player = {
  source: {
    item1: value,
    item2: value,
    item3: {
      item3-1: value
    }
  },
  playback: {
    parameter1: value,
    parameter2: value,
  }
}

What I'm trying to do is add values into player.source like this:

player.source.item4.item4-1 = 'something'

such that player.source looks like this:

  source: {
    item1: value,
    item2: value,
    item3: {
      item3-1: value
    },
    item4: {
      item4-1: 'something',
    },
  },

Thanks in advance for your help.

Upvotes: 1

Views: 245

Answers (2)

mhodges
mhodges

Reputation: 11116

You can do it like this - just create a function for generically adding a property/value to an object. If the property already exists, it just overwrites the value.

var value = 5;
var player = {
  source: {
    item1: value,
    item2: value,
    item3: {
      "item3-1": value
    }
  },
  playback: {
    parameter1: value,
    parameter2: value,
  }
}

function addProperty(obj, categoryName, value) {
  obj[categoryName] = value;
  return obj;
}

addProperty(player.source, "item4", addProperty({}, "item4-1", value));
console.log(player);

To add subsequent properties/values, you can access the newly created properties on your object like so:

addProperty(player.source.item4, "item4-2", 6);
addProperty(player.source.item4, "item4-3", 7);
// etc...

Upvotes: 1

kind user
kind user

Reputation: 41893

I'm not sure if it's not lil' bit too overcomplicated, but seems working.

var player = {source:{item1:"value",item2:"value",item3:{"item3-1":"value"}},playback:{parameter1:"value",parameter2:"value"}},
    obj = {
      'item4-1': 'something'
    };

    player.source.item4 = obj;
    console.log(player);

Upvotes: 1

Related Questions