how to add key value pair in the JSON object already declared - javascript

I have declared a JSON Object and added some key value pair in that like:
var obj = {};
and added some data into it like:
obj = {
"1":"aa",
"2":"bb"
};
But I want to add more key value pair in the same object, if I add key value pair same above mentioned then it replace the old one. So could any one please tell me how I can append data in the same JSON Object i.e. obj.

Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'

You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";

Object assign copies one or more source objects to the target object. So we could use Object.assign here.
Syntax: Object.assign(target, ...sources)
var obj = {};
Object.assign(obj, {"1":"aa", "2":"bb"})
console.log(obj)

Example code for json object:
var user = {'user':'barney','age':36};
user["newKey"] = true;
console.log(user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
for json array elements
Example code:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
users.map(i=>{i["newKey"] = true});
console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>

Hi I add key and value to each object
let persons = [
{
name : "John Doe Sr",
age: 30
},{
name: "John Doe Jr",
age : 5
}
]
function addKeyValue(obj, key, data){
obj[key] = data;
}
let newinfo = persons.map(function(person) {
return addKeyValue(person, 'newKey', 'newValue');
});
console.log(persons);

Please try following simple operations on a json, insert/update/push:
var movie_json = {
"id": 100,
};
//to insert new key/value to movie_json
movie_json['name'] = 'Harry Potter';
console.log("new key: " + movie_json);
//to update a key/value in movie_json
movie_json['id'] = 101;
console.log("updated key: " +movie_json);
//adding a json array to movie_json and push a new item.
movie_json['movies']=["The Philosopher's Stone"];
movie_json['movies'].push('The Chamber of Secrets');
console.log(movie_json);

You can add more key value pair in the same object without replacing old ones in following way:
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj["3"] = "cc";
Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:
var obj = {
"1": "aa",
"2": "bb"
};
var noOfItems = Object.keys(obj).length;
$('#btnAddProperty').on('click', function() {
noOfItems++;
obj[noOfItems] = $.trim($('#txtName').val());
console.log(obj);
});
https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/

possible duplicate , best way to achieve same as stated below:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
https://stackoverflow.com/a/47405116/3510511

Related

Push content of the object to array instead of the name of object

I have an empty object, and i want to push a key value pair to the array.
required.forEach(function(value){
if(value){
var tempVal = "event_info.schema." + value;
// console.log(tempVal);
var row = {tempVal: [properties[value]['type']]};
}
});
when I console.log(row) it shows
{ tempVal: [ 'string' ] }
However I want it to be the content of tempVal instead of "tempVal"
i.e. if tempVal = "name", I want row to be { name : ['string']}. How can I achieve this?
I have tried tempVal.eval() but that is an error. Can you point me to the right direction. Thanks in advance.
Objects can also be indexed with brackets.
tempVal = 'someString';
var obj = {};
obj[tempVal] = ['myArrayOfOneString'];
console.log(obj) // {'someString': ['myArrayOfOneString']}
Note that obj.something is equivalent to object['something']
This should do what you are looking for:
var
event_info = {
schema: {
name: "Yoda",
age: "150"
}
},
properties = {
name: {type: "male"},
age: {type: "old"}
}
//
var value = "name";
//
var tempVal = event_info.schema[value];
var row = {};
row[tempVal] = [properties[value]['type']];
console.log("tempVal:", tempVal);
console.log("row:", row);
console.log("row 'Yoda':", row["Yoda"]);
you will have to use array notation to set the property dynamically, like this:
var row = {};
row[tempVal] = [properties[value]['type']];
EDIT: as a commenter pointed out, you can condense this to one line (ES6 only):
var row = {[tempVal]: [properties[value]['type']]}

create an associative array in jquery

This is what I have so far and the shoe types are boots, wellingtons, leather, trainers (in that order)
I want to iterate through and assign the value so I haves something like
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
at the moment I just get an array of {3,0,1,3} which I can work with but it is not very helpful.
function shoe_types() {
var shoeArray = [];
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray.push ( parseInt($(this).val()) );
});
return shoeArray;
}
Check this function
function shoe_types() {
var shoeArray = {}; // note this
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray[$(this).attr('id')] = parseInt($(this).val()) ;
});
return shoeArray;
}
PS: Assuming $(this).attr('id') has all the shoe types
Associative array in javascript is the same as object
Example:
var a = {};
a["name"] = 12;
a["description"] = "description parameter";
console.log(a); // Object {name: 12, description: "description parameter"}
var b = [];
b["name"] = 12;
b["description"] = "description parameter";
console.log(b); // [name: 12, description: "description parameter"]
What you want is a function that will return an object {}
LIVE DEMO
function shoe_types(){
var shoeObj = {};
$('[name="number"]').each(function(){
shoeObj[this.id] = this.value;
});
return shoeObj;
}
shoe_types(); // [object Object]
You can try this to create an associate array in jquery
var arr = {};
$('[type=number]').each(function(){
arr.push({
$(this).attr('id'): $(this).val()
});
});
console.log(arr);
This will allow you to send your all data whatever you want to pass in array by ajax.
if $(this).attr('id') is the type of shoes you can try that
shoeArray[$(this).attr('id')] = parseInt($(this).val());

How to add an object property inside an array using a variable name for javascript?

How would I go about adding an object property inside an array using a variable name?
for example, I have":
var testArray = [];
var test1 = {
headerTest: results,
test1: test1Results
};
// add to test array
testArray.push(test1);
Now I need to add another object property to testArray[0] but instead using a variable name;
// I tried these options but not working....
var testProperty = $.trim($('#testProperty').test()); // single word
testArray[0][testProperty] = testResults;
testArray[0].testProperty = testResults;
considering your array and object:
//array
var testArray = [];
var test1 = {
headerTest: "val1",
test1: "val2"
};
You can use jQuery $.extend function to extend the current object test1, with another object that you create on the fly, for instance:
var newKey = "someNewKey";
var obj = {};
var newVal = "someValue";
obj[newKey] = newVal;
$.extend(testArray[0], obj);
the result:
[{
headerTest: "val1"
someNewKey: "someValue",
test1: "val2"
}]
The first method you propose should work fine(check your code if it's not, for instance there is no test method in jQuery core api):
var somethingToAdd = "newKey";
testArray[0][somethingToAdd] = "1";
the result:
[{
headerTest: "val1"
newKey: "1"
test1: "val2"
}]
How about this one:
testArray[0].(testProperty) = testResults;
Or
testArray[0].[testProperty + ''] = testResults;
You'll need to create a new object first because you cannot set the property of an undefined element.
testArray[0] = new Object();
testArray[0][testProperty] = testResults;

how check and substitute values in an array?

I have an array done with values from some radio buttons, say myArray = ["1","40","35"];
every value has his counterparts, say for instance 1 = "men", 2 = "women", 40 = "red hairs".
what's the best method to build another array where every values gets his counterpart?
so something like that myBrandNewArray = ["men","red hairs", …];
I should store my couples into variables for some maintenance, like
var "1" = "men", "2" = "women", … ;
but I don't know if this is a good approach…
ps. even pointing me to some resources will be great. Thank you.
I would keep a Hash of values
hash = { '1': 'Men', '2': 'Women' ... }
Then [ '1', '2', ... ].map( function(v) { return hash[v]; } );
IE9- will not accpet this, in this case you could just iterate in a for loop
Why don't you use an object as associative array?
var array = new Object();
array["1"] = "men"
array["40"] = "red hairs"
You can create an object like:
var arr = {
'1' : 'men',
'2' : 'women'
}
You can always access this easily like : arr['1'] == 'men'
if you want to create from existing arrays:
say myArray & myBrandNewArray
you can do something like
var arr = {};
foreach ( var i in myArray ) {
arr[myArray[i]] = myBrandNewArray[i];
}
i think this function
myArray = ["1","40","35"];
myBrandNewArray = myArray.map(function(element){ /* your code to get the right array 8/ })
source: http://www.tutorialspoint.com/javascript/array_map.htm
there is also a jQuery (cross browser) version of this function, for more details about that look here jQuery.map(myArray, function(value, index){ /*....*/ })
Use an object:
var val = {
1: "men",
40: "red hairs"
};
alert(val[1]);
alert(val[2])
;
well, finally I did this:
having
var numericalArray = ["1","50","45", …];
and
var couples = { "50" : "homme",
"1" : "femme",
"85" : "court",
…
};
I can call this and get a new array with coupled values:
function assignValues(numericalArray) {
var verbalArray = [];
for (var i=0; i<numericalArray.length; i++) {
var value = numericalArray[i];
verbalArray.push(couples[value]); // right, I can't check if the values exists
}
console.log('here my new array:', verbalArray);
}
thanks to have me pointed on use of an object.

Add JavaScript object to JavaScript object

I'd like to have JavaScript objects within another JavaScript object as such:
Issues:
- {"ID" : "1", "Name" : "Missing Documentation", "Notes" : "Issue1 Notes"}
- {"ID" : "2", "Name" : "Software Bug", "Notes" : "Issue2 Notes, blah, blah"}
- {"ID" : "2", "Name" : "System Not Ready", "Notes" : "Issue3 Notes, etc"}
// etc...
So, I'd like "Issues" to hold each of these JavaScript objects, so that I can just say Issues[0].Name, or Issues[2].ID, etc.
I've created the outer Issues JavaScript object:
var jsonIssues = {};
I'm to the point where I need to add a JavaScript object to it, but don't know how. I'd like to be able to say:
Issues<code here>.Name = "Missing Documentation";
Issues<code here>.ID = "1";
Issues<code here>.Notes = "Notes, notes notes";
Is there any way to do this? Thanks.
UPDATE: Per answers given, declared an array, and am pushing JavaScript objects on as needed:
var jsonArray_Issues = new Array();
jsonArray_Issues.push( { "ID" : id, "Name" : name, "Notes" : notes } );
Thanks for the responses.
var jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here
As my first object is a native JavaScript object (used like a list of objects), push didn't work in my scenario, but I resolved it by adding new key as follows:
MyObjList['newKey'] = obj;
In addition to this, may be useful to know how to delete the same object as inserted before:
delete MyObjList['newKey'][id];
Hope it helps someone as it helped me.
var jsonIssues = [
{ID:'1',Name:'Some name',Notes:'NOTES'},
{ID:'2',Name:'Some name 2',Notes:'NOTES 2'}
];
If you want to add to the array then you can do this
jsonIssues[jsonIssues.length] = {ID:'3',Name:'Some name 3',Notes:'NOTES 3'};
Or you can use the push technique that the other guy posted, which is also good.
// Merge object2 into object1, recursively
$.extend( true, object1, object2 );
// Merge object2 into object1
$.extend( object1, object2 );
https://api.jquery.com/jquery.extend/
If it's not an array of object you can do this:
let student= {
name : 'Mr. Anderson',
id: 35
}
student['grade'] = 10; //for a property.
Result:
student= {
name : 'Mr. Anderson',
id: 35,
grade:10
}
You also can add an object:
let student= {
personalData:{
//personal data key-value
}
}
let academicData = {
//academic data key-value
}
student['academicData'] = academicData;
Result:
student{
personalData{},
academicData{}
}
jsonIssues = [...jsonIssues,{ID:'3',Name:'name 3',Notes:'NOTES 3'}]
If you have properties in first obj and you have to add your objs to it, then Object.assign() will erase it.
To avoid this loss I've written a function below. Be aware, it copies nested objs by refference.
First you should add all objs you want to add to your's obj to an arr. You can do it easily by arr.push(). Then just use the Fn.
function addMyObjs (objInit, arrWithObjs) {
let map = new Map();
for (let [key, value] of Object.entries(objInit)) {
map.set(key, value);
}
arrWithObjs.forEach((item) => {
for (let [key, value] of Object.entries(item)) {
map.set(key, value);
}
});
return Object.fromEntries(map);
}
let objSecond = {id: 2,};
let obj = {
name: "Tolya",
age: 33,
sex: "man",
};
let obj3 = {"fruits": {"apples": true, "plums": false,}};
let arr = [obj, obj3];
objSecond = addMyObjs(objSecond, arr);

Categories

Resources