I retrieve this data from an API
{"city":"New York","type":["0","1","9"]}
I need to convert in this way:
{"type":{0:true,1:true,9:true},...}
I try with angular foreach in this way
var tmparr = [];
angular.forEach( $scope.path.type, function (value, key) {
tmparr.push(value + ":true")
});
$scope.checkfilters.type = tmparr
but in this way i have this result and it's not what i need
{"business_type":["0:true","1:true","9:true"]}
I don't know how to replace the [] with {} in my array
If I try to set var tmparr = {} I have undefined error in push function
Use bracket syntax
var tmparr = {};
angular.forEach( $scope.path.type, function (value, key) {
tmparr[value] = true;
});
$scope.checkfilters.type = tmparr;
You can loop through the type and then copy the values and assign it to true.
var original = {"city":"New York","type":["0","1","9"]};
var copy = {};
for(var i in original.type){
copy[original.type[i]] = true;
}
console.log(copy);
You can also use reduce with an object accumulator:
var data = {"city":"New York","type":["0","1","9"]}
const result = data.type.reduce((r,c) => (r[c] = true, r), {})
console.log(result)
Related
I have two array as follows
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
I want to combine these two array and covert it to the following format
var data={
"booktitle":"testtitle",
"bookid":"testid",
"bookauthor":"testauthor"
}
I want to insert this data to database using nodejs
var lastquery= connection.query('INSERT INTO book_tbl SET ?',data, function (error, results, fields) {
if (error) {
res.redirect('/list');
}else{
res.redirect('/list');
}
});
Please help me to solve this.
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
var finalObj = {};
field_array.forEach(function (eachItem, i) {
finalObj[eachItem] = data_array[i];
});
console.log(finalObj); //finalObj contains ur data
You also can use reduce() in a similar way:
var field_array=["booktitle","bookid","bookauthor"];
var data_array=["testtitle","testid","testauthor"];
var result = field_array.reduce((acc, item, i) => {
acc[item] = data_array[i];
return acc;
}, {});
console.log(result);
Here I explaned my code line by line..Hope it will help
var field_array = ["booktitle", "bookid", "bookauthor"];
var data_array = ["testtitle", "testid", "testauthor"];
//Convert above two array into JSON Obj
var jsondata = {};
field_array.forEach(function (eachItem, i) {
jsondata[eachItem] = data_array[i];
});
//End
//Store Jsondata into an array according to Database column structure
var values = [];
for (var i = 0; i < jsondata.length; i++)
values.push([jsondata[i].booktitle, jsondata[i].bookid, jsondata[i].bookauthor]);
//END
//Bulk insert using nested array [ [a,b],[c,d] ] will be flattened to (a,b),(c,d)
connection.query('INSERT INTO book_tbl (booktitle, bookid, bookauthor) VALUES ?', [values], function(err, result) {
if (err) {
res.send('Error');
}
else {
res.send('Success');
}
//END
i am having a json response from which i wanted to create new json object
response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
i wanted to achieve this after manipulating keys and value pair
lang_Arr =[
{Reuters_ID:"Reuters ID"},
{parity_one:"Parity One"},
{parity_level:"Parity level"}
];
i have tried doing it in two ways
1) in this getting error as unexpected tokken (.)
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value.keyName:value.Detail});
});
2) here getting unxepected token [
var Lang_arr =[];
angular.forEach(response, function(value, key) {
Lang_arr.push({value['keyName']:value['Detail']});
});
i have tried assigning the values seperatly too but it doesn't work there also
var Lang_arr=[];
var k ='';
var v ='';
var i = 1;
angular.forEach(response, function(value, key) {
k ='';
v ='';
i = 1;
angular.forEach(value,function(val,key){
if(i == 1 )
k = val;
if(i == 2)
v = val;
if(!empty(k) && !empty(v))
Lang_arr.push({k:v})
i++;
});
});
You can use javascript map function to map the objects to array
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var lang_Arr =[];
lang_Arr = response.map(function(o){
var obj = {};
obj[o.Detail] = o.keyName;
return obj;
})
console.log(lang_Arr)
With Angular forEach also you can achieve this functionality
var response = [
{Detail:"Reuters ID",keyName:"Reuters_ID"},
{Detail:"Parity One",keyName:"parity_one"},
{Detail:"Parity level",keyName:"parity_level"}
];
var modifiedArray = [];
angular.forEach(response, function(val, key) {
var res = {};
res[val.keyName] = val.Detail;
this.push(res);
}, modifiedArray);
console.log(modifiedArray)
Working Example in Fiddle
You have to assign it in the http call that gets the response
$htpp.get(....).then(function(response){
lang_arr = [];
response.forEach(function(obj){
var item = {obj.keyName : obj.detail};
lang_arr.push(item);
}
I am using the forEach to loop through it iterates through all of the objects but only writes the last one to the new object of log{}.
My Javascript
$http.get('data.json').success(
function (info) {
var log = {};
log.id= info.id;
log.profile = {};
angular.forEach(info.profile, function (value, key) {
console.log(key,value)
log.profile.inter = value.inter
}, log);
console.log(JSON.stringify(log));
}
);
Deprecation Notice
The $http legacy promise methods .success and .error have been deprecated. Use the standard .then method instead.1
$http.get('data.json')
.then(function onFulfilled(response) {
var info = response.data;
var log = {};
log.id= info.id;
log.profile = {};
angular.forEach(info.profile, function (value, key) {
console.log(key,value);
log.profile[key] = value.inter;
});
console.log(JSON.stringify(log));
}).catch ( function onRejected(response) {
console.log("ERROR ", response.status;
});
To save values into an associative array, use the key as the property accessor. For more information, see MDN JavaScript Reference -- Property Accessors
log.profile[key] = value.inter;
Well the reason is that you are not using an array, you need to push values into an one.
$http.get('data.json').success(
function (info) {
var log = {};
log.id= info.id;
log.profile = {};
log.profile.inter = []; //definition of array
angular.forEach(info.profile, function (value, key) {
console.log(key,value)
log.profile.inter.push(value.inter); //add values in array defined behind
}, log);
console.log(JSON.stringify(log));
}
);
There are more solutions, but for now putting values in array is enough.
var log = {};
log.id= info.id;
log.profile = {};
log.profile.inter = []; //definition of array
angular.forEach(info.profile, function (value, key) {
console.log(key,value)
//needed to add key
log.profile[key] = {};
}, log);
console.log(JSON.stringify(log));
}
I am trying to run a forEach function with data from a query and I want to set a variable for each object in that data to be able to use in a ng-repeat. I keep overriding the variable and cannot wrap my head around setting the variable for each one.
CategoryCardService.query({}, function (data) {
$scope.categoryCards = data;
angular.forEach(data, function (value) {
var categoryOccupancyPercent = $filter('number')(value.occupancy_percent * 100, 0);
var categoryTotalTurnover = value.total_turnover;
var doughnut_chart_min = 0;
var doughnut_chart_max = 0;
doughnut_chart_min = categoryOccupancyPercent;
doughnut_chart_max = 100 - categoryOccupancyPercent;
data.doughnutData = [doughnut_chart_min, doughnut_chart_max];
data.display = categoryOccupancyPercent + '%';
});
});
Pass in the key and assign like that.
CategoryCardService.query({}, function (data) {
$scope.categoryCards = data;
angular.forEach(data, function (value, key) {
// ...
data[key].display = categoryOccupancyPercent + '%';
});
});
How can I update this code to hold an array of values? I want to hold FIELDNAME and the VALUE.
I want to set / add to the list by doing the following - add a value to the array/list.
userFilters.setData(' lastname', 'smith');
userFilters.setData(' firstname', 'bob');
userFilters.setData(' Mi', 'D');
And have the object hold an Array of
'lastname','smith'
'firstname','bob'
'mi','D'
App.factory('userFilters', [function () {
var data = {};
var getData = function (field) {
return data[field];
};
var setData = function (field, value) {
data[field] = value;
};
return {
getData: getData,
setData: setData
}
}]);
You could recreate this fairly simply without any need for the methods you are creating.
Javascript Objects are designed to do exactly what you are looking for here.
App.factory('userFilters', function() {
return {};
});
Rather than using a getter and setter, you could instead get and set values with square bracket accessors.
// setting properties
userFilters['lastname'] = 'smith';
userFilters['firstname'] = 'bob';
userFilters['Mi'] = 'D';
// getting properties
userFilters['lastname']; // 'smith'
userFilters['firstname']; // 'smith'
If you want to be able to have full control of what happens at get/set time, you could look at intercepting these calls with internal getters and setters, providing you know the property names before hand.
Finally, you could also wrap your own get and set functions around the object in order to hide it. However, this would make more sense as a Service.
App.service('userFilters', function() {
var store = {};
this.get = function(key) {
return store[key];
};
this.set = function(key, value) {
store[key] = value;
};
});
If it's important that your factory/service exposes an array then I would recommend sticking to using an object to store keys and values, but adding an array export method.
App.service('userFilters', function() {
var store = {};
this.toArray = function() {
var records = [];
return Object.keys(store).map(function(key) {
records.push([key, store[key]]);
});
};
this.get = function(key) {
return store[key];
};
this.set = function(key, value) {
store[key] = value;
};
});
If you want to loop through the properties, you can use a for-in loop.
for(var key in userFilters) {
var value = userFilters[key];
console.log(key, value);
}
You can also check whether there any keys at all, using the Object.keys method.
Object.keys(userFilters); // ['lastname', 'firstname', 'Mi']
This will return an array of all the keys in the object. If it has length 0, then you know it's empty.
In order to use an array for storage you will need to update both getData and setData methods and define data as an array []:
App.factory('userFilters', [function () {
var data = [];
var getData = function (field) {
for(var i=0; i<data.length; i+=2) {
if(data[i] == field) {
return data[i+1];
}
}
return null;
};
var setData = function (field, value) {
data = data.concat([field, value]);
};
return {
getData: getData,
setData: setData
}
}]);