[javascript] Dynamically Add Variable Name Value Pairs to JSON Object

I have a json object full of ips like

var ips = {}

I then add ip objects to this object like so

ips[ipID] = {}

I then need to add dynamic/variable name value pairs to each ip so I am using code like this

var name; var value; var temp = {};
tmp[name] = value

My question is, how can I add these name value pairs/ tmp to my ipID objects so that my outcome turns out like

ipID = { name : value, anotherName : anotherValue }

This question is related to javascript object object-literal

The answer is


when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)

var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}

Here is a screenshot from testing in the Chrome console

screenshot


`enter code here`

Create Object from JSON String

_x000D_
_x000D_
var txt = '{"cart":{"sType":1, "produto":[{"pType":1, "pName":"produto original", "valor": 10.00},{"pType":1, "pName":"produto selecionado", "valor": 11.00}]}}';

var obj = JSON.parse(txt);
obj.cart.produto[0]['pName']='nome alterado';
obj.cart.produto[obj.cart.produto.length]={"pType":9, "pName":"produto adicionado", "valor": 19.00};

console.log(obj);

console.log(JSON.stringify(obj));



// compondo objeto JSON
var txt = '{"cart":{"sType":1, "product":[{"pType":1, "pName":"product genuine1", "pValue": 10.00},{"pType":1, "pName":"product genuine2", "pValue": 11.00}]}}';

// criando o objeto
var obj = JSON.parse(txt);

console.log('//log do objeto original');
console.log(obj);

// alterando o valor de uma "key", no caso a pName do produto[0]
obj.cart.product[0]['pName']='nome alterado';

// adicionando uma nova array
obj.cart.product[obj.cart.product.length]={"pType":9, "pName":"produto adicionado", "pValue": 19.00};

console.log('//log do objeto alterado');
console.log(obj);

console.log('//log do objeto alterado em txt');
console.log(JSON.stringify(obj));

// no html
document.getElementById('print').innerText = JSON.stringify(obj);
_x000D_
<html>
<body>

<h2>Manipulando um objeto</h2>
<p id="print"></p>
</body>
</html>
_x000D_
_x000D_
_x000D_

From what the other answers have proposed, I believe this might help:

var object = ips[ipId];
var name = "Joe";
var anothername = "Fred";
var value = "Thingy";
var anothervalue = "Fingy";
object[name] = value;
object[anothername] = anothervalue;

However, this is not tested, just an assumption based on the constant repetition of:

object["string"] = value;
//object = {string: value}

if my understanding of your initial JSON is correct, either of these solutions might help you loop through all ip ids & assign each one, a new object.

// initial JSON
var ips = {ipId1: {}, ipId2: {}};

// Solution1
Object.keys(ips).forEach(function(key) {
  ips[key] = {name: 'value', anotherName: 'another value'};
});

// Solution 2
Object.keys(ips).forEach(function(key) {
  Object.assign(ips[key],{name: 'value', anotherName: 'another value'});
});

To confirm:

console.log(JSON.stringify(ips, null, 2));

The above statement spits:

{
  "ipId1": {
    "name":"value",
    "anotherName":"another value"
  },
  "ipId2": {
    "name":"value",
    "anotherName":"another value"
  }
}

You can achieve this using Lodash _.assign function.

_x000D_
_x000D_
var ipID = {};_x000D_
_.assign(ipID, {'name': "value"}, {'anotherName': "anotherValue"});_x000D_
console.log(ipID);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


in Javascript.

    var myObject = { "name" : "john" };
    // { "name" : "john" };
    myObject.gender = "male";
    // { "name" : "john", "gender":"male"};

With ECMAScript 6 there is a better way.

You can use computed property names in object property definitions, for example:

var name1 = 'John'; 
var value1 = '42'; 
var name2 = 'Sarah'; 
var value2 = '35';

var ipID = { 
             [name1] : value1, 
             [name2] : value2 
           }

This is equivalent to the following, where you have variables for the property names.

var ipID = { 
             John: '42', 
             Sarah: '35' 
           }

I'm assuming each entry in "ips" can have multiple name value pairs - so it's nested. You can achieve this data structure as such:

var ips = {}

function addIpId(ipID, name, value) {
    if (!ips[ipID]) ip[ipID] = {};
    var entries = ip[ipID];
    // you could add a check to ensure the name-value par's not already defined here
    var entries[name] = value;
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to object-literal

How to fill a Javascript object literal with many static key/value pairs efficiently? JavaScript property access: dot notation vs. brackets? Self-references in object literals / initializers Adding/removing items from a JavaScript object with jQuery Dynamically Add Variable Name Value Pairs to JSON Object How to use a variable for a key in a JavaScript object literal? How to create an array of object literals in a loop? How can I add a key/value pair to a JavaScript object?