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
Related
I am using DataTables library and I have hard times in receiving data in a proper format so I am trying to adjust it before DataTable library tries to fetch data into table. I have an ajax call which returns an object of the following format:
data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]
And my desired output is: data:[ [{ "SomeKey":"SomeValue" } , { ...} ],[...] ]
I have tried JSON.stringify or eval method , but did not worked , also tried those 2 methods when return type was some sort of string but then it inserts \ before " so It does not convert to json. Any help or good tracks would be appreciated.
This has nothing to do with JSON. :-)
data is apparently an array of arrays of objects, where each object has properties valled Key and Value.
If you want to create a new array of arrays of objects, where the objects have a property named by the Key value whose value is the Value value, you can do that like this:
data = data.map(a => a.map(({Key,Value}) => ({[Key]: Value})));
That uses map on the arrays (both the outer and inner ones) and destructuring to pick out the Key and Value properties from each object in the subarrays, and uses computed property names to set the property name on the new object.
In ES5 and earlier, that would look like this:
data = data.map(function(a) {
return a.map(function(obj) {
var newObj = {};
newObj[obj.Key] = obj.Value;
return newObj;
});
});
You should look into Array.prototype.map (mdn)
let data = [[{Key: "SomeKey", Value: "SomeValue"}]];
let output = data.map(a => a.map(({Key, Value}) => ({[Key]: Value})));
console.log(output);
Note the [Key] syntax. To put it simply, whereas var x = 'key'; y = {x: 3} will assign the object {x: 3}, x = 'key'; y = {[x]: 3} will assign the object {key: 3}.
If you're receiving literally the string "data:[ [{ Key: "SomeKey" , Value: "SomeValue" } , { ...} ],[...] ]", then you may trim the first 5 characters ('data:') and then use JSON.parse.
The problem that I cant get access to array in array. Here is my Mongoose Schema:
const newSchema = mongoose.Schema({
email : String,
name : String,
array : [Number]
})
And here is data, which I put in array:
{
"array": [
-11,
"10,10,0",
"1"
]
}
Now I am trying to update the value "10" in the second row like this:
newAccount.array[3,0] = parseInt(someVariable)
or like this
newAccount.array[3][0] = parseInt(someVariable)
But the value doesn't changing in any case. How can I change it correctly?
This is a quick and dirty solution for your problem:
var obj = {
array: [
-11,
'10,0,0',
12
]
}
// splitting by ',' char
const newArray = obj.array[1].split(',')
// enter your new variable here.
newArray[0] = parseInt(someVariable);
// join them together so that we have the old structure back.
obj.array[1] = newArray.join(',');
console.log(obj);
a better approach would be to restructure your data enrichment in that way, that you don't have mixed types in there.
and the outcome:
I have two dimensional JSON array. I can take data from first dimension like data["dimension-1"] however i cannot take data from second dimension like: data["dimension-1"]["dimension-2"]. What is the proper way to take single row from second dimension of my array?
data["dimension-1"]["dimension-2"] - seems to be rather an object - hence it should look like :
var data = {
"dimension-1" : {
"dimension-2" : 'value'
}
}
data["dimension-1"]["dimension-2"] // will display 'value'
and then your way it ok.
but if it's an array
var data =[[1,2], [3,4]]
then one should access it like (the indexes are NUMERIC - not strings or any other):
data[0][1] // will display 2
You have an object with properties that are also a mixture of arrays or objects. If you are trying to extract the ID of the data property, which is an array, then you will need to select the property, enter the array (first item is 0), which returns another object. Then just select the property.
You'll need something like the following in your use case: -
objectName.data[0].id
or
objectName["data"][0]["id"];
This is for extracting the ID from within the data attribute in data like this (that you provided): -
var objectName = {
"total_pages": 1424,
"total_rows": 1424,
"data": [
{
"id": 1525,
"television_id": 1,
// other stuff
"categories": [
{
"id": 170,
"title": "title"
},
{
"id": 4,
"title": "message"
}
]
}
]
}
A 2 dimensional JSON array looks like this:
[
["a", "b", "c"],
["d", "e", "f"],
["g", "h", "i"]
]
Say you want to access the last column in the second column. i.e. "f", then you need to access it by number not name. i.e.:
data[1][2]
EDIT:
Stictly speaking, my original answer is correct. Your 2 dimensional array may be accessed by indices.
However, knowing the format of your data now, I would recommend either:
Use a library (e.g. lodash) to give you simple and expressive ways to query your data
or create your own function. e.g.:
var category = getCategory(x.data, 1525, 170);
function getCategory(data, id, catId) {
return data
.filter(d => d.id === id)
.map(d => d.categories
.filter(c => c.id === catId)
.map(c => c.title)
.shift()
)
.shift()
}
Good luck!
I have an array that contains objects, like this:
[{
"first" : 1
},
{
"second" : 2
},
{
"third" : 3
}]
I want to turn this into two arrays, with indexes matching based on these values, such as:
["first","second","third"]
[1,2,3]
I can iterate through this and get the object keys and values, but I feel there's gotta be a slick way in lodash to do this, that I don't know of. Any suggestions? Thank you!
It seems like you just need to map over the object and call keys() and values()
You will get the first array like:
var items = [{a: "1"},{b: "blah",c: "what"},{d: "3"}]
keys = _(items).map(_.keys).flatten().value()
returns ["a","b","c","d"]
And the second array like:
values = _(items).map(_.values).flatten().value()
returns ["1","blah","what","3"]
For a non-lodash solution:
var arr = [{"first" : 1},{"second" : 2},{"third" : 3}];
var keys = arr.map(function(el){return Object.keys(el)[0];});
var vals = arr.map(function(el){return el[Object.keys(el)[0]];});
For the opposite problem (multiple arrays into one array of objects), see Merge two arrays into an array of objects with property values
Assuming that your object shape is always {"label": value}, then you can use this vanilla JavaScript:
var data = [{"first" : 1},{"second" : 2},{"third" : 3}];
var labels = data.map(function(entry) {
return Object.keys(entry)[0];
});
var values = data.map(function(entry) {
return entry[Object.keys(entry)[0]];
});
Your data structure seems sub-optimal based on your comments. I would recommend an alternate structure:
var data = [
{'label': 'first', 'value': 1},
{'label': 'second', 'value': 2},
{'label': 'third', 'value': 3}
]
Which is then trivial to pick out the labels and values into separate pieces in normal JavaScript:
var labels = data.map(function(entry) {
return entry.label;
});
var values = data.map(function(entry) {
return entry.value;
});
Or if you really want to use lodash:
var labels = _.pluck(data, 'label');
var values = _.pluck(data, 'value');
Hopefully you can see that this revised structure makes the JavaScript much simpler whether you use lodash or not.
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.