Dynamically add to JS Object with multiple elements - javascript

I have a Object to dynamically fill my DropDown list.
var myOptions = [
{ name: Projekte[1][1], value: "val1" },
{ name: Projekte[2][1], value: "val2" },
{ name: Projekte[3][1], value: "val3" },
{ name: Projekte[4][1], value: "val4" },
{ name: Projekte[5][1], value: "val5" },
{ name: Projekte[6][1], value: "val6" },
{ name: Projekte[7][1], value: "val7" },
{ name: Projekte[8][1], value: "val8" },
{ name: Projekte[9][1], value: "val9" },
{ name: Projekte[10][1], value: "val10" }
];
it looks like ther will be up to 100 Projects when the code is in charge, so how can I set name and value of this Object to the right length?
what i tried before was this:
var anzahlproj =100; //how many project i get
var myOptions = [
{ name: Projekte[1][1], value: "val1" }
];
for(var i=2;i<anzahlproj + 1; i++){
myOptions[name] +="Projekte["+i+"][1]",
myOptions[value] += "val"+i;
}
add something to a normal Object is no problem, but how can I add something with multiple elements?
I use: JQuery 1.11.1, JQuery Mobile 1.4.3

var myOptions = [], i;
for (i = 1; i <= 100; i++) {
myOptions.push({name: Projekte[i][1], value: "val" + i});
}

Try this code
var anzahlproj = 100; //how many project i get
for (var i = 2; i < anzahlproj + 1; i++) {
var myOption = new Option(Projekte[i][1], "val" + i.toString());
myOptions.append($(myOption));
}

Related

Finding objects in a nested array along with their position

I've taken the following sample from a different question. And I am able to identify the object. But I also need to find our the position of that object. For example:
var arr = [{
Id: 1,
Categories: [{
Id: 1
},
{
Id: 2
},
]
},
{
Id: 2,
Categories: [{
Id: 100
},
{
Id: 200
},
]
}
]
If I want to find the object by the Id of the Categories, I can use the following:
var matches = [];
var needle = 100; // what to look for
arr.forEach(function(e) {
matches = matches.concat(e.Categories.filter(function(c) {
return (c.Id === needle);
}));
});
However, I also need to know the position of the object in the array. For example, if we are looking for object with Id = 100, then the above code will find the object, but how do I find that it's the second object in the main array, and the first object in the Categories array?
Thanks!
Well, if every object is unique (only in one of the categories), you can simply iterate over everything.
var arr = [{
Id: 1,
Categories: [{Id: 1},{Id: 2}]
},
{
Id: 2,
Categories: [{Id: 100},{Id: 200}]
}
];
var needle = 100;
var i = 0;
var j = 0;
arr.forEach(function(c) {
c.Categories.forEach(function(e) {
if(e.Id === needle) {
console.log("Entry is in position " + i + " of the categories and in position " + j + " in its category.");
}
j++;
});
j = 0;
i++;
});
function findInArray(needle /*object*/, haystack /*array of object*/){
let out = [];
for(let i = 0; i < haystack.lenght; i++) {
if(haystack[i].property == needle.property) {
out = {pos: i, obj: haystack[i]};
}
}
return out;
}
if you need the position and have to filter over an property of the object you can use a simple for loop. in this sample your result is an array of new object because there can be more mathches than 1 on the value of the property.
i hope it helps
Iterate over the array and set index in object where match found
var categoryGroups = [{
Id : 1,
Categories : [{
Id : 1
}, {
Id : 2
},
]
}, {
Id : 2,
Categories : [{
Id : 100
}, {
Id : 200
},
]
}
]
var filterVal = [];
var needle = 100;
for (var i = 0; i < categoryGroups.length; i++) {
var subCategory = categoryGroups[i]['Categories'];
for (var j = 0; j < subCategory.length; j++) {
if (subCategory[j]['Id'] == findId) {
filterVal.push({
catIndex : i,
subCatIndex : j,
id : needle
});
}
}
}
console.log(filterVal);
Here is solution using reduce:
var arr = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 }, ] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }, ] } ]
const findPositions = (id) => arr.reduce((r,c,i) => {
let indx = c.Categories.findIndex(({Id}) => Id == id)
return indx >=0 ? {mainIndex: i, categoryIndex: indx} : r
}, {})
console.log(findPositions(100)) // {mainIndex: 1, categoryIndex: 0}
console.log(findPositions(1)) // {mainIndex: 0, categoryIndex: 0}
console.log(findPositions(200)) // {mainIndex: 1, categoryIndex: 1}
console.log(findPositions(0)) // {}
Beside the given answers with fixt depth searh, you could take an recursive approach by checking the Categories property for nested structures.
function getPath(array, target) {
var path;
array.some(({ Id, Categories = [] }) => {
var temp;
if (Id === target) {
path = [Id];
return true;
}
temp = getPath(Categories, target);
if (temp) {
path = [Id, ...temp];
return true;
}
});
return path;
}
var array = [{ Id: 1, Categories: [{ Id: 1 }, { Id: 2 },] }, { Id: 2, Categories: [{ Id: 100 }, { Id: 200 }] }];
console.log(getPath(array, 100));
.as-console-wrapper { max-height: 100% !important; top: 0; }

loop through objects and find specified properties

I have an array of objects. A typical object looks like:
{
id: x
name: y
employeeInfo: {
employeeNumber: x
startDate: x
}
salary: x
}
Now I'm trying to loop through it and get the name, employeeNumber and salary.
My column variable, to be used in the loop, is:
public columns: Array<any> = [
{title: 'id', name: 'id'},
{title: 'employeeInfo.employeeNumber', name: 'employeeInfo.employeeNumber'},
{title: 'salary', name: 'salary'}]
I'm trying to loop with
item[column.name]
but of course this would result in item['emplyeeInfo.employeeNumber'], which would result in a undefined.
Can someone help?
You can split the column name and reduce, like:
column.name.split('.').reduce((res, part) => res[part], item)
split returns an array (in our case ['employeeInfo', 'employeeNumber']) so we can reduce that array using the item as the initialValue.
The reduce() method applies a function against an accumulator and each
element in the array (from left to right) to reduce it to a single
value.
Something like this:
var employees = [
{
id: 1,
name: 'Charlie',
employeeInfo: {
employeeNumber: 123,
startDate: '2017-01-23'
},
salary: 2500
},
{
id: 2,
name: 'John',
employeeInfo: {
employeeNumber: 456,
startDate: '2017-02-26'
},
salary: 3500
}
];
var columns = [
{title: 'id', name: 'id'},
{title: 'employeeInfo.employeeNumber', name: 'employeeInfo.employeeNumber'},
{title: 'salary', name: 'salary'}
];
function buildTable() {
var table = $("<table>");
var header = $("<tr>");
for(var i = 0; i < columns.length; i++) {
header.append("<th>" + columns[i].title + "</th>");
}
table.append(header);
for(var i = 0; i < employees.length; i++) {
var employee = employees[i];
var row = $("<tr>");
for(var y = 0; y < columns.length; y++) {
var properties = columns[y].name.split('.');
var value = employee;
for(var x = 0; x < properties.length; x++) {
value = value[properties[x]];
}
row.append("<td>" + value + "</td>");
}
table.append(row);
}
$("#result").append(table);
}
buildTable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Can't you just parse/split the name on the dot and for each part, you get the object, fetch its property and reiterate while there is a next property to fetch?
I ended up using a "simplify" approach. i.e. filter through the array, grab what I need, put it in a new object, put it in a temporary array and finally replace the complex array with the simple array.
try this:
var myObject = {
id: "x",
name: "y",
employeeInfo: {
employeeNumber: "inner employeeNumber",
startDate: "inner date",
},
salary: "x"
}
for(var id in myObject) {
if(typeof myObject[id] === "object") {
for(var innerId in myObject[id]){
console.log(innerId + ": " + myObject[id][innerId]);
}
} else {
console.log(id + " " + myObject[id]);
}
}

AngularJS making a sum between objects

I am quite new to AngularJS and have been building the following:
app.js
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
Now I would like to take the values of both of these object and substract them from each other!
So either have all the values of Inkomsten added to another and the ones from Uitgiften.. and then substract or individually(Which is prefered... So taking the value of uitgiften and then from inkomsten and substract them.)
I have been tinkering around with it but I can't seem to find a solution for it. Anyways, not in Angular :D
I hope you guys can help
Clarification:
Sorry. I would like to have
uitgiften.value[1]+uitgiften.value[2]+uitgiften.value[3]
and then inkomsten.value[1]+inkomsten.value[2]+inkomsten.value[3]
and then the outcome of these 2 summs would need to be outcomeInkomsten-outcomeUitgiften=endOutcome
Since your values are strings, you will need to cast them to numbers. Here's what I would do:
var result = 0;
$scope.inkomsten.forEach(function(item){
result += Number(item.value);
});
$scope.uitgiften.forEach(function(item){
result -= Number(item.value);
});
Since it is an array you could add a function to the Array prototype.
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
Array.prototype.sum = function (prop) {
var total = 0;
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += parseInt(this[i][prop]);
}
return total;
}
$scope.endOutcome = $scope.inkomsten.sum("value") - $scope.uitgiften.sum("value");
The Fiddle:
http://jsfiddle.net/U3pVM/20778/
you can use array method reduce:
var $scope={};
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
var res = $scope.inkomsten.reduce(function(total, current){
return total + Number(current.value);
}, 0)
console.log(res)
this will give you the numeric total of an Array;
and then you can do the same with second array, and subtract the two;
well you can use
var results=0;
for(i=0;i<$scope.inkomsten.length;i++){
results+=Number($scope.inkomsten[i].value);
}
for(i=0;i<$scope.uitgiften.length;i++){
results-=Number($scope.uitgiften[i].value);
}
console.log(results);
You can try this below code
$scope.inkomsten= [
{ name: 'Salaris',value:'500' },
{ name: 'Toeslag',value:'200' },
{ name: 'Inkomsten',value:'211' },
{ name: 'Weekend', value:'22' }
];
$scope.uitgiften= [
{ name: 'eten',value:'120'},
{ name: 'kat',value:'230'},
{ name: 'schildpad', value: '300'},
{ name: 'huur', value: '200'}
];
$scope.sum1 = 0;
$scope.sum2 = 0;
for(i in $scope.inkomsten){
$scope.sum1 = $scope.sum1 + parseInt($scope.inkomsten[i].value);
}
for(i in $scope.uitgiften){
$scope.sum2 = $scope.sum2 + parseInt($scope.uitgiften[i].value);
}
$scope.endOutcome = $scope.sum1 - $scope.sum2;
alert($scope.endOutcome);

After removing an element from array using splice. its not resetting.Is my code has any mistake

A drop down contains an array value. If i select one value from drop down it will remove that value from array its working. But on click of reset button it should reset with old values .Here is my code
HTML code
<html>
<head>
<script src="angular/angular.js"></script>
<script src="js/controllers.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="exerciseTypeCtrl">
<select id="exerciseSuperCategory" data-role="listview" ng-options="Lay.id as Lay.value for Lay in Layer " ng-model="itemsuper" ng-change="changeData(itemsuper)">
</select>
<input type="button" ng-click="resetLayer()" value="Reset"/>
</div>
</body>
</html>
angularjs controler code
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('exerciseTypeCtrl',function($scope)
{
$scope.Layer = [
{ id: 1, value: '0.38'},
{ id: 2, value: '0.76'},
{ id: 3, value: '1.14'},
{ id: 4, value: '1.52'},
{ id: 5, value: '1.9'},
{ id: 6, value: '2.28'},
{ id: 7, value: '2.66'},
{ id: 8, value: '3.04'},
{ id: 9, value: '3.42'},
{ id: 10, value:'3.8'},
{ id: 11, value: '4.18'},
{ id: 12, value: '4.56'}
];
$scope.changeData = function(value)
{
var coating = $scope.Layer;
if(coating != null)
{
var j = coating.length;
while(j>0)
{
j =j-1;
var make = coating[j]['id'];
var present = 0;
if(make == value)
{
coating.indexOf(make);
coating.splice(j,1);
}
}
}
}
$scope.resetLayer -function()
{
$scope.Layer = $scope.Layer;
}
});
</script>
using splice i am removing the dropdown selected value. but on click of button its not resetting
Thanks in advance
You should take a copy of variable while you intialize/get Layer data
var copyOfLayer = angular.copy($scope.Layer);
Then while reseting it you need to do assign old array to the $scope.Layer also you need to rewrite your resetLayer function to below
$scope.resetLayer = function() {
$scope.Layer = angular.copy(copyOfLayer)
}
Working Plunkr
Mistake is here:
$scope.resetLayer -function()
Should be
$scope.resetLayer =function()
I am formatting your code:
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('exerciseTypeCtrl',function($scope)
{
$scope.Layer = [
{ id: 1, value: '0.38'},
{ id: 2, value: '0.76'},
{ id: 3, value: '1.14'},
{ id: 4, value: '1.52'},
{ id: 5, value: '1.9'},
{ id: 6, value: '2.28'},
{ id: 7, value: '2.66'},
{ id: 8, value: '3.04'},
{ id: 9, value: '3.42'},
{ id: 10, value:'3.8'},
{ id: 11, value: '4.18'},
{ id: 12, value: '4.56'}
];
var resetArray = $scope.Layer;
$scope.changeData = function(value)
{
var coating = $scope.Layer;
if(coating != null)
{
var j = coating.length;
while(j>0)
{
j =j-1;
var make = coating[j]['id'];
var present = 0;
if(make == value)
{
coating.indexOf(make);
coating.splice(j,1);
}
}
}
}
$scope.resetLayer =function()
{
$scope.Layer = restArray;
}
});
</script>
You have done a mistake in this line where you are assigning your function to the resetLayer variable
$scope.resetLayer -function(){}
This should instead be
$scope.resetLayer =function(){};
Enjoy!

Build JSON Object from string containing multi-dimensional

I have an array of name/value objects (below). The names are formatted to represent multi-dimensional array.
I need to build a full JavaScript object out of it(bottom).
[{
name: "getQuote[origin]",
value: "Omaha,NE"
},
{
name: "getQuote[destination]",
value: "10005"
},
{
name: "getQuote[country]",
value: "us"
},
{
name: "getQuote[vehicles][0][year]",
value: "1989"
},
{
name: "getQuote[vehicles][0][make]",
value: "Daihatsu"
},
{
name: "getQuote[vehicles][0][model]",
value: "Charade"
},
{
name: "getQuote[vehicles][0][count]",
value: "1"
}]
Into something like this:
{getQuote :
{ origin : Omaha},
{ destination : 10005},
{vehicles : [
{
year : 1989,
make: Honda,
model : accord
},
{
//etc
}]
n
You can do it manually, like this:
var source = [ /* Your source array here */ ];
var dest = {};
for(var i = 0; i < source.length; i++)
{
var value = source[i].value;
var path = source[i].name.split(/[\[\]]+/);
var curItem = dest;
for(var j = 0; j < path.length - 2; j++)
{
if(!(path[j] in curItem))
{
curItem[path[j]] = {};
}
curItem = curItem[path[j]];
}
curItem[path[j]] = value;
}
dest is the resulting object.
Check it working here: http://jsfiddle.net/pnkDk/7/

Categories

Resources