may I know how to push var obj= [{}] in .each? for example like this.
$.each(maintasks_row, function(index, maintasks_val) {
obj.push([{
"name" : maintasks_val.task_name,
"desc" : "",
"values" : [{
"from" : "/Date("+maintasks_val.time_start+")/",
"to" : "/Date("+maintasks_val.time_end+")/",
"label": maintasks_val.task_name,
"customClass" : "ganttRed"
}]
}]);
});
I'm using this for $(".gantt").gantt({source: obj});
On this site the var data is [{}] is this an object? and how can I insert it?
thank you
.push does not require you delcare it as an array ( like you tried obj.push([{ - unless of course you are pushing an array into an array
Just simply ...
obj.push({"name" : maintasks_val.task_name, ..
adds a new single item intto the array
Update as comment , yes, declare obj as a typeof array first
var obj=[];
This is now the same as the data array you have shown in your docs example - and we can now .push() into it.
Related
I'm new to AngularJS and JSON. I'm stuck in this stage where I want to filter unnecessary fields in the JSON.
I used code in my controller :
var data = $scope.choices; // Is an array
var datav = (JSON.stringify(data)); // array converted into a string need to be filtered
alert(datav);
If I alert(datav) am getting JSON data which mentioned below.
[{"title":"g","$$hashKey":"object:3"},{"id":"choice2","$$hashKey":"object:6","title":"ghgh"},{"id":"choice3","$$hashKey":"object:11","title":"fgh"}]
I want only "title" I don't want $$hashKey and id. How to do this?
You can use angular.toJson instead of JSON.stringify which would omit $$hashkey for you.
angular.toJson
Serializes input into a JSON-formatted string. Properties with leading $$ characters will be stripped since AngularJS uses this notation internally.
Like this,
var myobj = [{
"title": "g",
"$$hashKey": "object:3"
}, {
"id": "choice2",
"$$hashKey": "object:6",
"title": "ghgh"
}, {
"id": "choice3",
"$$hashKey": "object:11",
"title": "fgh"
}]
console.log(angular.toJson(myobj))
console.log(JSON.stringify(myobj))
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
Edit: In case you want to only show some property, use Array.map as described in other answers. angular.toJson would only be helpful here when you want to omit just $$hashkey retaining everything else.
You can use Array.map() function to achieve what you want, and return only the properties you are interested in
var data = [{"title":"g","$$hashKey":"object:3"},{"id":"choice2","$$hashKey":"object:6","title":"ghgh"},{"id":"choice3","$$hashKey":"object:11","title":"fgh"}];
var datav = data.map(d => ({title: d.title}));
console.log(datav)
Try this
<html>
<head>
<script Src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<script>
var app=angular.module("myapp", []);
app.controller("namesctrl", function($scope){
var data = [{"title":"g","$$hashKey":"object:3"},{"id":"choice2","$$hashKey":"object:6","title":"ghgh"},{"id":"choice3","$$hashKey":"object:11","title":"fgh"}];
var data1 = data.map(d => ({title: d.title}));
console.log(data1);
});
</script>
</head>
<body ng-app="myapp" ng-controller="namesctrl">
</body>
</html>
You can use Array.prototype.map.
When you first receive your array:
const data = [
{title: "hello" , "unwanted" : 34},
{title: "hello" , "unwanted" : 35},
{title: "hello" , "unwanted" : 36},
{title: "hello" , "unwanted" : 37},
]
const wanted = data.map( d => {
return {title: d.title}
});
console.log(wanted);
var data = $scope.choices.map(function(index,item){
return {id: item.id};
});
this is how you can map the desired object you need out of choices array
I believe you are using a third party library. My guess is Angular Material which adds a similar $$haskey property to the dropdown array values. Ideally this shouldn't make any change to your array and you should still be able to get your properties on array object.
But if you specifficaly want to remove these unwanted properties you should create a new array out of this array using a .map function. Example:
var newArray= orginalArray.map(element => ({title: element.title}));
You can take out as many properties as you want and leave unwanted properties. Your new array is a complete different reference from old array.
Hope this helps
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
guys i know it is dummy question but i spent a lot of hours and cant reach .. i ha ve json array and i want for example to access the elements of second row which are lname2 fname2 90 feedback2 .. this is the array var json = [ {
"lname" : "lname1",
"fname" : "fname1",
"age" : 10,
"feedback" : "feedback1"
}, {
"lname" : "lname2",
"fname" : "fname2",
"age" : 90,
"feedback" : "feedback2"
}, {
"lname" : "lname3",
"name" : "fname3",
"age" : 30,
"feedback" : "feedback3"
}
You have an array of objects - so iterate the array, access the object properties:
for (var i = 0; i < json.length; i++) {
console.log(json[i].fname);
}
To specifically access the second element of the array, specify the index:
var fname = json[1].fname;
You can access 2nd row by index
json[1]
From what I can see, this variable is not a JSON, but simply a javascript array of objects. To access a data in it, you'll have to use json[X].lname for exemple, where X is the index of the object you want to reach.
A JSON is a string of characters representing different type of data, such as arrays and objects. To decode such a string, you could use JSON.parse().
You can find more informations about JSON here : http://www.json.org/
Hope this helps!
Use the below code
json[1].lname
json[1].fname
json[1].age
json[1].feedback
Also what ever you have posted is not a JSON its an parsed result of JSON. JSON is ultimately a string. all the data is converted into one big string. Later when you parse the json you will get the result as in your post.
Explaining the code
Note that variable json is like var json = [] , this [ ] is used to create a array, Hence the variable json is an array and we can access the elements by inex
Here [1] referes to the index of the array. As your json is an array. We use index numbers to access the elements in the array. And the indexes start from 0. So your second element will be in the index 1, 3rd will be in 2 and so on...
Now json[1] will return the second element so..
json[1] = {
"lname" : "lname2",
"fname" : "fname2",
"age" : 90,
"feedback" : "feedback2"
}
note the { } this refers to an object, this { } is used to create an object. Now to access the property values of the object we use the . operator. hence the code json[1].lname , json[1].fname and so on..
I have a backbone collection in the below format, comma separated values in one of the attributes
var my_collection = {
{
"name" : "test1",
"field" : "a,b,c"
},
{
"name" : "test2",
"field" : "a,c"
},
};
I wanted to filter the attribute 'field' of value 'a' from the above collection, so that it should return test1 and test2.
I tried using var filtered = my_collection .where({field: 'a'}); this will do the exact match of "field:a" only.
Any solution to filter the test1 and test2 when the user given the value "field:a"
Thanks in advance.
Use _.filter -- it's like _.where, except lets you specify a function as the predicate. Then use split along with indexOf to check if "field" contains your item:
my_collection.filter(function(x) {
return x.field && x.field.split(',').indexOf("a") != -1;
})
Fiddle
I have a string containing a list of dictionary.
I want to compare by checking their keys not value. is there any way to do that.
data = '[{ "group1" : "T1"}, { "group1" : "T2"}, { "group2" : "T3"}]';
how can i compare these dictionaries on the basis of their keys. for example, i have used:
dataObj = eval(data); //generate 3 objects for data.
here dataObj[0] will refer to object of { "group1" : "T1"}
to do it i have done following code:
for(i=0;i<dataObj.length;i++){
if (dataObj[i].key == dataObj[i].key){ //<-- i am not getting what to do to compare their keys i.e. "group1" and "group1"
//my other statements
}
}
Do not use eval but JSON.parse](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse) instead. If it's not available in some old browsers there are plenty of implementation that are less vulnerable to attack than just eval.
Saying that, having:
var data = '[{ "group1" : "T1"}, { "group1" : "T2"}, { "group2" : "T3"}]';
var array = JSON.parse(data);
Will generate an Array of Object, each of them has one own property called group1 or group2. To be clear:
var myobj = {"group1" : "T1"}
Is an Object literal, and it's exactly the same of:
var myobj = new Object();
myobj.group1 = "T1";
So, as you can see, there is no key property anywhere.
It's not clear what you want to compare, also because the third object seems have a different property's name.
Updated:
About your comment, the point here is that there is no "object key" but just object's properties. It means, you need to know the name of the "key" in advance in order to use it:
array[0].group1 === array[1].group1 // false, one is "T1", one is "T2"
If you want to have a key properties that contains the value "group1", than your objects needs to be different:
var data = '[{"key" : "group1", "value": "T1"}, {"key": "group1", "value" : "T2"}, { "key" : "group2", "value" : "T3"}]'
Then, you can have:
var array = JSON.parse(data);
array[0].key === array[1].key // true, both are "group1"
array[0].value === array[1].value // false, one is "T1", one is "T2"
When i create a new object from an existing object, then append a new attribute, why does it update the earlier one?
Is their a solution that does not involve changing my code much?
Here is my example jsfiddle.
var data = [
{
"id" : 1,
"name" : "carrot",
"price" : 0.10,
"stock" : 12,
"bgLocation" : "-1px -54px"
},
{
"id" : 2,
"name" : "fennel",
"price" : 1.20,
"stock" : 6,
"bgLocation" : "-146px -52px"
}
]
var item = data[0];
item.added = 4;
//data[0] should not contain the added attribute.
$('body').append(JSON.stringify(data[0]));
The variables item and data are just references pointing to the same object. By calling.
var item = data[0];
you're not copying the object, you just create a new reference on the object that is addressed with data[0]. Therefore
item.added = 4;
will change the object bot vraiables point to.
Here
How do I correctly clone a JavaScript object?
are some detailed information on how to copy objects in javascript.
Because all you get is a reference to the original object, not a copy. Thus, if you update this reference, you are implicitly updating the original object.
You can easily create a copy using $.extend():
var item = $.extend({}, data[0]);
DEMO.