My jquery array is showing like
[Object { qty=1, item_id="76", add_ons="2", add_on_price:20}, Object { qty=1, item_id="76", add_ons="1",add_on_price:40}]
I want to make an array like this
[object{ qty=2,item_id=76,add_ons_price=60}]
I need to add the qty,add_ons_price in single object.
any help will be appreciated.
this will group objects based on property item_id
var result = {};
for (var i = 0, len = myObjects.length; i < len; i++) {
var obj = myObjects[i];
if (result[obj.item_id] === undefined) {
result[obj.item_id] = [];
}
result[obj.item_id].push(obj);
}
now you can add the required values and push the result in new object
Related
I am trying to create an array of objects. One object property is a function, which I want to change value of depending on which number in the array the object is.
When I try to use the 'i' value from the for loop, this is not being maintained in the function as a number. It is remaining a variable.
var array = [];
for (var i = 0; i<number; i++){
array[i].someFunction = function(i) {console.log(i)}}
However, when I call the value held in that property (i.e.):
console.log(array[2].someFunction)
It returns {console.log(i)} instead of {console.log(2)} which is what I want it to do.
Basically you had some problems in your code, like:
not defining number
using var instead of let
not defining the object
using the same value as parameter of the function
here you have the working solution.
var array = [];
// numbers was not defined.
const number = 10;
// use let instead of var
for (let i = 0; i < number; i++) {
// you are not instantiating your object, here is an example.
array[i] = {
"foo": "bar",
"index": i,
}
// you have to change i to j, because if you use i
// it will be the parameter of the function
array[i].someFunction = function(j) {
console.log('index: ', i);
console.log('parameter: ', j)
}
}
// we see the function
console.log(array[2].someFunction)
// we call the function succesfully
array[2].someFunction(100);
It's still referencing i, which has since changed to (number - 1). Save the value somewhere you know it's not subject to change- perhaps in the object itself:
var array = [{}, {}, {}];
for(var i = 0; i < array.length; i++){
array[i].index = i;
array[i].someFunction = function(){console.log(this.index);}
}
//and see that it's working...
for(var i = 0; i < array.length; i++){
array[i].someFunction();
}
When i try to create two dimensional array in javascript using loop, it gives me following error:
Cannot set property 'indexis' of undefined
Code:
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i]; //assuming headingsArray exist
indexes[i]['valueis'] = rows[0][i]; //assuming rows exist
}
}
You need to create the inner arrays/objects as well, or else index[i] is undefined, so index[i]['indexis'] will throw an exception.
var indexes = [];
for (var i = 0; i < headingsArray.length; i++) {
indexes[i] = {}; //<---- need this
if (headingsArray[i].toLowerCase().indexOf('name') != -1) {
indexes[i]['indexis'] = i;
indexes[i]['headingis'] = headingsArray[i];
indexes[i]['valueis'] = rows[0][i];
}
}
You described it as a multidimensional array, but you're using it as though it's an array of objects (because you're accessing named properties, instead of numbered properties). So my example code is creating objects on each iteration. If you meant to have an array of arrays, then do indexes[i] = [], and interact with things like indexes[i][0] rather than indexes[i]['indexis']
You need an object before accessing a property of it.
indexes[i] = indexes[i] || {}
indexes[i]['indexis'] = i;
define temp var with field initialise to null & use push() function of JavaScript
for (var i = 0; i < headingsArray.length; i++) {
var temp={indexis: null,headingis:null,valueis:null};;
if (headingsArray) {
temp['indexis'] = i;
temp['headingis'] = headingsArray[i]; //assuming headingsArray exist
temp['valueis'] = rows[0][i];
indexes.push(temp);
}
}
How to add values to an empty array? I have tried the following but it is not working:
var student = [{}];
for (var i = 0; i < 5; i++) {
student[i].name = i;
student[i].id = "1";
student.push(student[i]);
}
var a = JSON.stringify(student);
alert(a);
It give output 6 time repeated last values not 5 time :
'[{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"},{"name":4,"id":"1"}]'
var student = [{}];
This creates a javascript array containing one empty object
student[i].name = i;
student[i].id = "1";
For i = 0, this alters that empty object.
student.push(student[i]);
You then push that altered object to the array it already exists in. You now have two identical values in the array.
Two items after first push. This is repeated five times.
Pushing an item adds it to the array. There's usually no point in pushing an element that's already in the array. Create a new object and push that. The array doesn't have to be pre-populated with an empty object to modify.
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
name: i,
id: '1'
});
}
In your original code, you are setting the object at student[i]'s values, then just pushing it again onto the array, then setting those values all over again.
You need to push a new object each time:
var student = [];
for (var i = 0; i < 5; i++) {
student.push({
id: i,
name: i
});
}
var a = JSON.stringify(student);
alert(a);
You are using the same name for the list and the new object. When you change the name of the list to students, your problem is fixed. Solution below:
var students = [{}];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
try ;
var students = [];
for (var i = 0; i < 5; i++) {
student = {}
student.name = i;
student.id = "1";
students.push(student);
}
var a = JSON.stringify(students);
alert(a);
Your array is not empty. It already contains an object. Maybe the problem is easier to see if we put the object in an extra variable and omit the the loop:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj.name = 2;
student.push(obj)
The question is: How many objects are we creating here? The answer is one, namely var obj = {};. We then add some properties to the object (name) and add it to the array (student.push(obj)).
What comes next is crucial: We change the existing properties of the object and assign different values to it. Then we add the object to the array again. Even though student contains two elements, but they refer to the same value (which can be easily verified with student[0] === student[1]).
If you want to create an array of different objects, you have to create those objects. In our example this would be:
var student = [];
var obj = {};
obj.name = 1;
student.push(obj);
obj = {}; // <- create a new object
obj.name = 2;
student.push(obj)
For your code that means that you have to create a new object in each iteration of the loop, not just one outside of it.
Reading material about arrays and objects:
Eloquent JavaScript - Data structures: Objects and Arrays
MDN - Working with objects
MDN - Array object
Since you are pushing object, its reference change every time to current value so at last it shows the output as last value.
Try this
var student = [{}];
for (var i = 0; i < 5; i++) {
var obj = new Object();
obj.name = i;
obj.id = "1";
student.push(students);
}
var a = JSON.stringify(student);
alert(a);
I need to temporarily track the state of 5 objects in JavaScript. Each of these objects has a GUID as its id. Because of this, I was hoping to create an array of key/value pairs that I can work with. The key of each pair would be the id of each object. The value of each pair would be a boolean value. My problem is, I am really not sure how to do this in JavaScript. Currently, I have the following:
var myKeyValuePairs;
var myObjects = getMyObjects();
for (var i=0; i<myObjects.length; i++) {
var id = myObjects[i].id;
// What do I do now?
}
How do I build an array of key/value pairs in JavaScript?
var myKeyValuePairs = {},
myObjects = getMyObjects(),
i, obj
for (i=0, len = myObjects.length; i < len; i++) {
obj = myObjects[i]
myKeyValuePairs[obj.id] = obj
}
Or if you really want to use an array you could do something like
var myKeyValuePairs = getMyObjects.map(function (obj) {
return {
key: obj.id,
value: obj
}
})
I want to sort a JSON object/array (shown below as myArray), upon values from another array - very close to the MYSQL query MYSQL WHERE IN(1,2,3). I was able to get a great answer by Nick Craver on how to sort by one property and value, but how can I do this with multiple values from my other array?
Here's my dataset Json array:
var myArray = [
{
"id":"2",
"name":"My name",
"properties":{"prop1":"value1"}
}];
And the array which I want to sort upon (serialized, coming straight from a form):
var sortArray = [ { "prop1":"value1","prop2":"value2" }];
The current sorting function as it looks right now (courtesy Nick Craver):
function filterDataset(property, value){
var newArray = [];
for (var i = 0, l = myArray.length; i < l; i++) {
if (myArray[i].properties[property] === value)
newArray.push(myArray[i]);
}
return newArray;
}
Here's how I managed to fix it:
function filterDataset2(properties){
var newArray = [];
for (var i = 0, l = dataset.length; i < l; i++) {
$.each(properties, function(){
if (dataset[i].properties[this.name] === this.value)
newArray.push(myArray[i]);
});
}
return newArray;
}
This may not be what you mean, but if you have a known list of properties, could you just || your comparison? Say you have 2 properties...
function filterDataset(property, value){
var newArray = [];
for (var i = 0, l = myArray.length; i < l; i++) {
if ((dataset[i].egenskaper[property1] === value) || (dataset[i].egenskaper[property2] === value) )
newArray.push(myArray[i]);
}
return newArray;
}
Otherwise if the length of the sorting array is unknown you could use a array.find type method that will return true if the property is found within the array in question. If it returns true, just push that value on your newly sorted array.