How to append to json object in JavaScript - javascript

How can I append to a json object.
I define the JSON as follows:
$scope.usergroupJson = {'groupId':1,'name':'CEO'}
I would like to append {'groupId':2,'name':'Director'} to the usergroup. I have tried:
$scope.usergroupJson.push({'groupId':2,'name':'Director'});
But I get an undefined error. I know this is trivial but any help would be appreciated. Thanks in advance

We can use like this
var json = {};
json["employees"] = [];
var usergroupJson = json["employees"];
usergroupJson.push({
'groupId': 1,
'name': 'President'
});
usergroupJson.push({
'groupId': 2,
'name': 'Vice-President'
});
usergroupJson.push({
'groupId': 3,
'name': 'Product Manager'
});

you must usergroupJson to be array
$scope.usergroupJson = [{'groupId':1,'name':'CEO'}]

Related

Delete field from JSON file in node

I want to delete a field from a JSON file in node. Suppose my file looks like this
{
'name': John Doe,
'nickname': Johnny
}
and if I say delete('nickname'); I want it to look like this.
{
'name': John Doe
}
How should I go about doing this? Also is there a way to check how many elements are left in the file? And if so how could I delete the whole file if it is empty?
update: this is the code I'm debugging
var data = require(pathToFile);
var element = data[deleteKey];
delete element;
fs.writeFileSync(pathToFile, JSON.stringify(data, null, 4), 'utf8');
res.end(deleteKey + ' was deleted');
console.log(JSON.stringify(data, null, 4));
To check how many elements are left in the JSON file, you can use this:
Object.keys(jsonArray).length;
To delete an element however:
var json =
{
'name': John Doe,
'nickname': Johnny
}
var key = "name";
delete json[key];
As for deleting a file, you can use ajax and call a server-side file to accomplish this.
You can just delete it...
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny'};
delete myObj.nickname;
OR
var myObj = { 'name': 'John Doe', 'nickname': 'Johnny' };
delete myObj["nickname"];
OUTPUT
{name: "John Doe"}

Angular unintentional binding/object mirroring

So I am working on a project using AngularJS where I need to be able to compare the values of an object in the scope with it's previously recorded values. I'm doing this through an algorithm such as the one below:
function() {
var data = [
{ id: 1, key: 'value', foo: 'bar'},
{ id: 2, key: 'value', foo: 'bar'}
]
$scope.oldTarget = data[0];
$scope.target = data[0];
}
Now if I were to do:
function() {
$scope.target.foo = 'fighters';
if ($scope.target != $scope.oldTarget) console.log('Target was modified');
console.log($scope.target);
console.log($scope.oldTarget);
}
It will output:
{ id: 1, key: 'value', foo: 'fighters'}
{ id: 1, key: 'value', foo: 'fighters'}
My assumption is that AngularJS is automatically binding the two variables target and oldTarget and mirroring any changes done to target to oldTarget. Is this the case, and if so, is there anyway for me to prevent this? If not, what am I doing that's causing it to do this?
This is not related to Angular, it's default JavaScript behavior. You are referencing the same object. If you intend to modify it without changing the source, you need to clone the object.
Take a look:
What is the most efficient way to clone an object?
Most elegant way to clone a JavaScript object
I assume that this is not angular, this is just how it works, because $scope.oldTarget and $scope.target both is links to the same object.
var test = {foo : 'bar'};
var newTest = test;
newTest.foo = 'changed';
console.log(test);
Th output is: "Object {foo: "changed"}"
http://jsfiddle.net/rf0ac6zf/
Looks like your array element is being referenced "by reference". So create new instances of the element like this:
$scope.oldTarget = $.extend(null,data[0]);
$scope.target = $.extend(null,data[0]);

JSON.stringify set root element

I want to convert my object into a JSON String where the root element should be the name of my object.
var data = {
name: 'qwertz',
age: 23,
skills: [
'html', 'css'
]
}
var json = JSON.stringify(data);
The output is:
{"name":"qwertz","age":23,"skills":["html","css"]}
But I want this:
{"data":{"name":"qwertz","age":23,"skills":["html","css"]}}
Can someone give me a hint how to reach this? Thanks you :)
As simple as that:
var json = JSON.stringify({ data: data });
Try this
JSON.stringify({'data':data})

Functional way of joining two js object arrays based on common id

I am trying to acheive something similar to SQL table join,
in the most elegant (functional) way, preferably with underscore.js,
so no for loops please.
I need to merge objects from two different arrays, matched upon a common identifier.
For example, given:
var basic = [{
id: '1',
name: 'someName',
},
{...} ]
var ext= [{
id: '1',
job: 'someJob',
},
{...} ]
Result should be:
var combined = [{
id: '1',
name: 'someName',
job: 'someJob',
},
{...} ]
Thanks!
Map, findWhere and extend should do the trick:
var combined = _.map(basic, function(base){
return _.extend(base, _.findWhere(ext, { id: base.id} ));
});
Edit:
If performance is an issue create a hash of the extended values:
var extHash = _.reduce(ext, function(memo, extended, key){
memo[extended.id] = extended;
return memo;
}, {});
and use like so:
var combined = _.map(basic, function(base){
return _.extend(base, extHash[base.id]);
});
Fiddle
NO LOOP : http://jsfiddle.net/abdennour/h3hQt/2/
basic=basic.sort(function(a,b){return a.id-b.id});
ext=ext.sort(function(a,b){return a.id-b.id});
var combined=basic.map(function(e,i){return inherits(e,ext[i]) });
Known that ,inherits are as following:
function inherits(base, extension)
{
for ( var property in base )
{
extension[property] = base[property];
}
return extension ;
}

Adding data to existing object mapping a contanst key/value

In my first function, I am getting a few pieces of information and pushing them to my object.
autoArry.push({
id: countTxns,
txnID: txnID,
account: buyersAccount,
data1: '',
data2: '',
data3: ''
});
At this point, I dont have the information from data1, data2, or data3 but I created them in the object anyway.
Later in my script, I want to be able to fill in those data values when i collect it throughout other functions.
The one thing that I will have that is the same in every function is the txnID.
I assume I will have to Map that somehow and then add additional data that way.
Would anyone be able to explain how I could do this?
Thanks Much
Iterate and check for a match :
function otherFunction(txnID) {
for (var i=0; i<autoArray.length; i++) {
if (autoArray[i].txnID == txnID) {
autoArray[i].data1 = 'something 1';
autoArray[i].data2 = 'something 2';
autoArray[i].data3 = 'something 3';
}
}
}

Categories

Resources