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
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
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_
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.
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_
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;
}
Source: Stackoverflow.com