Appending to an object in a list of objects - javascript

I have a javascript array that contains objects and looks like this:
[{‘sku':’ASD',’price': 10.99,’name':’Hot Sauce',’quantity': 1}, {‘sku':’JKL',’price': 8.99,’name':’Chilli Peppers',’quantity': 1}, {‘sku':’UIO',’price':’10.50',’name': "Sip 'n' Sizzle T-Shirt",’quantity': 1}]
I have a variable that contains the subtotal for the entire order and I would like to append it to each object for database purposes.
I tried this, but it messed everything up.:
var allProdData = prodData.push({total: total})
I assume I have to a use a for loop, but I'm not quite sure how to do it.

I had the same problem a couple of days ago try this
for(key in Objectname){
var allProdData = prodData.push(Objectname[key].total)
}
Put the correct objectname

First give a correct format for your array like below:
var arr = [{sku:'ASD',price: 10.99,name:'Hot Sauce',quantity: 1}, ...]
Then loop the array, calculate the total and format a new array
var arrNew = [];
for (var i = 0; i < arr.length; i++){
var total = arr[i].price * arr[i].quality;
arrNew.push({sku:arr[i].sku,price: arr[i].price,name:arr[i].name,quantity: arr[i].quality, total:total});
}

Related

Naming objects inside of an array dynamically

I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!
Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...
First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];

How to create multiple objects based on dynamic data?

Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Insert complex value to an existing array in JavaScript

I need to create a list of struct type (complex model) on JavaScript using ASDP.NET MVC3
var myItems = new Array(#Model.Count());
var CreatedItem;
for (i = 1 ; i<= #Model.Count()-1;i++)
{
CreatedItem = {
'DayPartID': i,
'Name': $("#Name_"+i).val(),
'IsEnable': $("#IsEnable_"+i).val(),
'Time': $('#timepicker-'+ i).val()
};
myItems.push(CreatedItem);
alert(myItems[i]);
}
Problem is that I can not obtain "myItems" filled correctly after repetitive structure "for" ends.
You're initializing your array like:
var arr = new Array(2);
Then you do:
arr.push("foo");
This will give you:
[ undefined, undefined, "foo" ]
Either change the initialaztion to an empty array like:
var myItems = [];
Or don't push, but set, like:
myItems[i] = CreatedItem;
Also, your loop starts at 1 - that's weird. Change to:
for (i = 0 ; i < #Model.Count(); i += 1) {

How to add dynamically growing array into another dynamic array

In my project i have arrays for date1, date2 and so on upto one month dates as shown below
var day1= [4,5,6,11];
var day2= [7,8,9,12];
var day3= [10,11,12,14];...
var day30= [1,2, 3, 4];
In the above each array exact size we dont know that may increase or decrease and i need to pass these values to the one more set of arrays like
var data1= [day1[0], day2[0], day3[0]];
var data2= [day1[1], day2[1], day3[1]];
var data3= [day1[2], day2[2], day3[2]];...
var data30= [day1[30], day2[30], day3[30]];
As per the day array size data array size will increase.
How to solve this issue any help..?
Consider using an object instead of variables:
var days = {
day1: [4,5,6,11],
day2: [7,8,9,12],
...
day30: [1,2, 3, 4]
};
Then you can do something like:
var data30 = [];
var i = 0;
while ( days.hasOwnProperty('day' + ++i) ){
data30.push(days['day' + i]);
}
Though given the sample data, data30 won't have any members because the first array has no member at index 30.
Check out JavaScript's push method.
http://www.w3schools.com/jsref/jsref_push.asp

Categories

Resources