Dibish
Dibish

Reputation: 9293

Add array key value in Javascript

I have a network array like the following way

"network_contents": [

      {
         "facebook":"contents to all pages",

      },
      {
         "twitter":"twiter contents",

      },
      {
         "linkedin":"linked in contents",

      }
]

I would like to add some keys to that array bases on its content. If it is facebook the key should be facebook, if it is twitter key should be twitter. But not sure how to do it.

My requirement is to access network array contents, but it may or may not content these facebook, twitter, linked in values. I need to access its values. When i assign a key value will be easy to fetch its contents. So i tried this way to loop through the array

message.network_contents.forEach( function (nwContent) {
                        if(nwContent.twitter) {
                            console.log('nw content', nwContent.twitter);
                        }

                    })

can i create an array in this foreach loop like the following way.

{
    "data": [
        {
            "facebook": {
                "facebook": "facebook content"
            },
            "twitter": {
                "twitter": "twitter content"
            }
        }
    ]
}

Your help is much appreciated thanks

Upvotes: 0

Views: 74

Answers (2)

Amadan
Amadan

Reputation: 198324

Implementation of what I said in the comment:

var oldsies = stuff.network_contents;
var newsies = stuff.network_contents = {};
oldsies.forEach(function(network) {
  var name = Object.keys(network)[0];
  newsies[name] = network;
});

Upvotes: 1

Amir Popovich
Amir Popovich

Reputation: 29836

You gave an example of a JS object and not a dictionary and therefore cant add key-values. You need something like this:

    var network_contents = [];
    network_contents["facebook"] = {config1: {name:"config1", value:"value1"}};
    network_contents["twitter"] = {config2: {name:"config2", value:"value2"}};

example: network_contents["facebook"].config1.value; // will return "value1"

You can covert your object to a dictionary easily.

Upvotes: 0

Related Questions