1

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.

1
  • 2
    There is no such thing as an "associative array" in JavaScript. What you have is an object, and you're adding properties to it. Commented Mar 15, 2017 at 22:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Close.. I want to create a new property 'item4' under 'source' and add properties to it.
@ymdahi I knew I have overcomplicated it. Fixed.
awesome, trying this out now
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.