How to use loop to create obj in javascript - javascript

My aim is to create something like this
$rootScope.customMarkers = [
{address: "1600 pennsylvania ave, washington DC", "class": "my1"},
{address: "600 pennsylvania ave, washington DC", "class": "my2"},
];
Here is part of my code, yet this does not work
for (var i = 0; i < cart.length; i++) {
$rootScope.customMarkers = [{
address: cart[i].address,
"class": cart[i].class,
}];
}
Could anyone give me some clues or just give me some key words?

This code will not work since you have to push objects to array:
$rootScope.customMarkers = [];
for (var i = 0; i < cart.length; i++) {
$rootScope.customMarkers.push({
address: cart[i].address,
"class": cart[i].class,
});
}

Your current code overwrites $rootscope.customMarkers on each loop iteration with a new array containing just one entry.
This is a classic use of map:
$rootScope.customMarkers = cart.map(function(entry) {
return {address: entry.address, class: entry.class};
});
...assuming cart is an array. If it isn't, it's just array-like, you might use Array.from:
$rootScope.customMarkers = Array.from(cart, function(entry) {
return {address: entry.address, class: entry.class};
});
...or a boring old loop:
$rootScope.customMarkers = [];
for (var i = 0; i < cart.length; ++i) {
$rootScope.customMarkers[i] = {address: cart[i].address, class: cart[i].class};
}
Side note: As of ES5, both uses of class above are valid, you don't have to put quotes around one but not the other. If you need to handle old engines that may not handle it, you need to handle it in both places: "class": entry["class"].

You can simply use foreach loop for angularjs
angular.forEach(cart, function(value, key) {
$rootScope.customMarkers.push({
address : value.address,
class : value.class
});
});
It's done.

Related

JavaScript: how can we push an array inside an array?

I am facing an issue in small requirement. I want to create a JSON array in below format using JavaScript for loops.
var payloadTest = {
"people": [{
"pic": "sap-icon://employee",
"name": "Ravi",
"role": "team member",
"appointments": [{
"start": new Date("2017", "0", "21", "0", "0"),
"end": new Date("2017", "0", "21", "23", "59"),
"title": "Meet John Miller"
}, {
start: new Date("2017", "0", "18", "0", "0"),
end: new Date("2017", "0", "18", "23", "59"),
title: "Team meeting",
}]
]
}
};
Im trying with below code using for loops. But it is not working.
var itemsArr = [];
var headArr = [];
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
payloadTest.people.appointments = itemsArr;
Can someone please help me to create an array using for loops in the above JSON Format.
Note :: appointments array count may increase based on the results coming from backend
In:
payloadTest.people.appointments = itemsArr;
you are trying to assign the appointment array as a property of an array of people. Instead, you should be assigning it as a property of an (or every?) individual person.
So you could do:
payloadTest.people[0].appointments = itemsArr;
but that would only give one of the people an array of appointments. It's unclear from your code whether you want each person to have a reference to (or copy of) the same appointment array, one person to have it, or whether you thought you were creating separate arrays for each person. To do the later, you'd need a nested loop.
Update
You probably want to move the declaration/initialization of itemsArr inside the loop, so that each person has their own array (otherwise, modifications to one person's appointment array would be made to everyone's array).
Then, you would likely want to initialize them with a unique test array - so a nested loop (say j from 0 to i), creating incrementally larger lists of appointments for each person. But as it's just test data you're creating, it's really up to you what belongs in there.
Change your code according to below code
for (var i = 0; i < resultSet.length; i++) {
var obj = {};
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
headArr.push(itm);
obj.start=resultSet[i].Begda;
obj.end=resultSet[i].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
itm.appointments = itemsArr; // Added
//headArr.push(itemsArr);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
Removed
payloadTest.people.appointments = itemsArr;
Because it assigns appointments to person array not to each person. You have to add appointments to each person record to added in loop
itm.appointments = itemsArr;
See below snippet for your multiple appointment. I used dummy data.
Change according to your data format.
var headArr = [];
var payloadTest = [];
var resultSet = [{'Rowlabel' : 'Ravi', 'RowId' : 'team member', 'appointments' :[{'Begda' : 'test', 'Endda' : '1'}, {'Begda' : 'test', 'Endda' : '1'}]}, {'Rowlabel' : 'name', 'RowId' : '1', 'appointments' : [{'Begda' : 'test', 'Endda' : '1'}]}];
for (var i = 0; i < resultSet.length; i++) {
var itm={};
itm.pic="sap-icon://employee";
itm.name=resultSet[i].Rowlabel;
itm.role=resultSet[i].RowId;
var itemsArr = [];
for (var j = 0; j < resultSet[i].appointments.length; j++) {
var obj = {};
obj.start=resultSet[i].appointments[j].Begda;
obj.end=resultSet[i].appointments[j].Endda;
obj.title=resultSet[i].RowId;
obj.type="Type02";
obj.tentative=false;
itemsArr.push(obj);
}
itm.appointments = itemsArr; // Added
headArr.push(itm);
}
payloadTest.people = headArr;
/*payloadTest.people.appointments = itemsArr;*/ // Removed
console.log(headArr);
Hope it helps.

for-in loop to for loop or forEach

Ok I have the following scenario. I need to convert this for-in loop to either a for loop or forEach. I have tried a few different examples but can't seem to get the code to append to the page. The for-in loop will work however for the code I need to write, it is not allowed.
This is an example variable
var work = {
"jobs": [{
"employer": "Java",
"title": "Script",
"dates": "2017",
"description": "description",
}
}
This is the code that I have to work. Currently in a for-in loop but need it into a for or forEach loop.
function displayWork() {
for (job in work.jobs) {
//create new div for work experience
$("#workExperience").append(HTMLworkStart);
//concat employer and title
var formattedEmployer = HTMLworkEmployer.replace("%data%",
work.jobs[job].employer);
var formattedTitle = HTMLworkTitle.replace("%data%", work.jobs[job].title);
var formattedEmployerTitle = formattedEmployer + formattedTitle;
$(".work-entry:last").append(formattedEmployerTitle);
var formattedDates = HTMLworkDates.replace("%data%", work.jobs[job].dates);
$(".work-entry:last").append(formattedDates);
var formattedDescription = HTMLworkDescription.replace("%data%",
work.jobs[job].description);
$(".work-entry:last").append(formattedDescription);
});
}
displayWork();
It looks like you will have an array of jobs inside the work object, although your example is missing the closing square bracket for the jobs array, and it might be clearer if you had more than one entry in the array.
Given a data structure like this:
var work = {
jobs: [
{
employer: "example1"
},
{
employer: "example2"
},
{
employer: "example3"
}
]
}
You can use a simple for loop based on the fact that the jobs array will have consecutive integer keys starting at zero:
for (var i = 0; i < work.jobs.length; i++) {
// do stuff with current job in work.jobs[i]
var current_employer = work.jobs[i].employer;
}

JavaScript nested for-loop to add values to an object

I have encountered a situation in my code where I have three java script variables in which two are arrays and one is a single string variable. The following are their structure:
var selectedUser = $('#Employees_SelectedValue').val(); //It has one one value "12121"
var selectedCountries = $('#Countries_SelectedValue').val(); //It has multiple values ["IND", "USA"]
var selectedSourceSystems = $('#SourceSystems_SelectedValue').val(); //It has multiple values ["SQL", "ORACLE", "MySQL"]
What I have to do is to add these values in a class on the basis of selectedUser such as User is same for all the values but the remaining two are different as:
var userSettings = { userName: selectedUser, userCountry: selectedCountries, userSourceSystem: selectedSourceSystems };
The situation is to add the values from this class into an array in such a way that every userCountry and userSourceSystem will come as a single entity such as:
{ userName: "12121", userCountry: "IND", userSourceSystem: "SQL" },
{ userName: "12121", userCountry: "USA", userSourceSystem: "ORACLE" },
{ userName: "12121", userCountry: "", userSourceSystem: "MySQL" }
I'm trying the approach of nested-for loop to handle this scenario like:
for (var i = 0; i < selectedCountries; i++)
{
for (var j = 0; j < selectedSourceSystems; j++)
{
userSettings.userName = selectedUser;
//Add i and j values
}
}
Please suggest an effective approach other than this.
You may set up a 3×n matrix ( a 2d array) and rotate it by 90 degrees:
var matrix = [[selectedUser],selectedCountries,selectedSourceSystems];
var result =
Array(//set up a new array
matrix.reduce((l,row)=>Math.max(l,row.length),0)//get the longest row length
).fill(0)
.map((_,x)=> matrix.map((row,i) => row[i?x:x%row.length] || ""));
Result
If result should contain objects, then map the 2d array to objects:
var objects = result.map(([a,b,c])=>({userName:a,userCountry:b,userSourceSystem:c}));
result
Small explanation:
row[i?x:x%row.length] || ""
Actually does the following:
If were in the first row ( i=0 ) ("12121")
take whatever value of the array (x%row.length), so basically always "12121"
if not, try to get the value of the current column(x)
if row[x] doesnt exist (||) take an empty string ("")
A more basic approach:
var result = [];
for(var i = 0,max = Math.max(selectedCountries.length,selectedSourceSystems.length);i<max;i++){
result.push({
userName:selectedUser,
userCountry:selectedCountries[i]||"",
userSourceSystem:selectedSourceSystems[i]||""
});
}
result
I believe it would be better to restructure your userSettings object in more natural way:
userSettings: {
name: "userName",
countries: ["USA", "IND"],
userSourceSystems: ["MySQL", "Oracle"]
}
Then you can fill it with settings from your inputs like this
for (item in selectedCountries)
userSettings.countries.push(item)
for (item in selectedCountries)
userSettings.userSourceSystems.push(item)

Filter JSON with unique key/values

I have a JSON object structured as such:
var theSchools = {
Bradley University: "bru",
Knox College: "knox",
Southern Illinois University Edwardsville: "siue",…
}
What I am trying to achieve is a way of retrieving the key, in this case the school name, by supplying the value, the schools 'code.'
It does not appear that I will be able to have this restructured correctly, i.e.
var theSchools = [
{
schoolName:"Bradley University",
schoolCode: "bru"
}
{
schoolName: "Knox College",
schoolCode: "knox"
}
]
so I'm kind of stuck with what I got.
I know the following code is incorrect, but it's essentially what I want to achieve:
if(getParameterByName("schoolId").length>0){
var schoolid = getParameterByName("schoolId");
var schoolName= theSchools.schoolid;
jQuery("h1").after("<h2>Welcome to <strong>"+schoolName+"</strong></h2>")
}
You can use a for...in loop to loop over each property in the object, and return the property name if the value matches:
var theSchools = {
"Bradley University": "bru",
"Knox College": "knox",
"Southern Illinois University Edwardsville": "siue"
};
function findSchool(code) {
for (var s in theSchools) {
if (theSchools[s] === code)
return s;
}
return null;
}
document.getElementById('school').innerText = findSchool('knox');
<div id="school"></div>
The question is if you really need it this way (see answer #James), here's what you requested:
var theSchools = {
"Bradley University": "bru",
"Knox College": "knox",
"Southern Illinois University Edwardsville": "siue"
}, schoolMap = {};
for (var schoolName in theSchools) {
var code = theSchools[ schoolName ];
schoolMap[ code ] = schoolName;
}
document.body.innerHTML = schoolMap["bru"]; // Bradley University
You don't have to use a for loop to check if property exists. Use hasOwnProperty method.
if (theSchools.hasOwnProperty("Knox College")) {
//do stuff
}
Working example: https://jsfiddle.net/7q9czdpc/

javascript find in array

I have an array like this:
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];
I want to find the location of the movie that's released in 1999.
Should return 1.
What's the easiest way?
Thanks.
You will have to iterate through each value and check.
for(var i = 0; i < movies.length; i++) {
if (movies[i].ReleaseYear === "1999") {
// i is the index
}
}
Since JavaScript has recently added support for most common collection operations and this is clearly a filter operation on a collection, instead you could also do:
var moviesReleasedIn1999 = movies.filter(function(movie) {
return movie.ReleaseYear == "1999";
});
assuming you're not interested in the indexes but the actual data objects. Most people aren't anyways :)
.filter is not supported in all browsers, but you can add it yourself to your code base:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Compatibility
Built in? Use loops.
You want to get fancy? Linq to Javascript: http://jslinq.codeplex.com/
Something like:
function findMovieIndices(movies, prop, value) {
var result = [];
for(var i = movies.length; i--; ) {
if(movies[i][prop] === value) {
result.push(i); // personally I would return the movie objects
}
}
return result;
}
Usage:
var indices = findMovieIndices(movies, "ReleaseYear", "1999");
Maybe this gives you some idea for a more generalized function (if you need it).
Since you've also tagged it with jQuery, you could use the 'map' function:
var movies = $.map(movies,function(item,index){
return item.ReleaseYear == 1999 ? index : null;
});
This will return an array of indexes for all movies with the year of 1999. If you wanted the movies themselves as an array:
var movies = $.map(movies,function(item){
return item.ReleaseYear == 1999 ? item : null;
});
If functional style programming is applicable:
_.indexOf(_.pluck(movies, "ReleaseYear"), "1999")
Because it's that simple. The functional toolkit that is underscore.js can be very powerful.
_.indexOf , ._pluck
You'll have to create your own searching function.
Array.prototype.findMovieByYear = function (findYear) {
for (var i = 0; i < this.length; i++) {
// this actually returns the element, maybe you just want
// to return the array index ( the i param )
if (this[i].Release == findYear) return this[i];
}
return null;
// or return -1 or whatever if you want to return the index
};
// now you can call:
movies.findMovieByYear('1998');
// and that should return
{ Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" }
Of course, this way of doing it actually affects every array you create.. which is maybe not what you want.. you can create your own array object then ...

Categories