push array object into localstorage - javascript

var arr = [];
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
arr.push(obj);
localStorage.setItem('buy',JSON.stringify(arr));
The problem with above code is when executing it will replace the existing array object, how to add new obj into the array if the order_id is not the same?

New Answer:
var arr = [];
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
$change = 'no'; for(i=0; i<arr.length; i++){ if(obj.order_id == arr[i].order_id){ obj.qty = obj.qty + arr[i].qty; arr[i] = obj; $change ='yes'; } }
if($change == 'no'){ arr.push(obj); }
console.log(arr);
And for saving it in localstorage see my answer here: push multiple array object into localhost?
Old Answer:
The best solution would be to make 'arr' an object with the order_id being the key of the object. You get something like this:
var arr = {};
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
arr[obj.order_id]= obj;
console.log(arr);
This will only replace the order if the order_id is the same. If you really want and array, you have to make a function that goes through the array and checks every order_id.

Related

Javascript loop through an array of objects and return the first value

I have created a function that is supposed to loop through an array of objects and return the first value of each object.
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
return sheetData[i][0];
}
data.push(obj);
}
It's only returning the first item in the first row/column. Any clues on what I'm missing?
You could use Object.keys together with Array#map to get just the first key value from each object.
data = sheetData.map(v => v[Object.keys(v)[0]]);
Working example:
var arr = [{foo: 'bar', bar: 'foo'},{foo: 'war', bar: 'foo'},{foo: 'mar', bar: 'foo'}],
res = arr.map(v => v[Object.keys(v)[0]]);
console.log(res);
How about this solution. Hope it helps!
var sheetData = [{name : "Mike", id: 10},{name : "Laura", id: 23},{name : "carl", id: 25},{name : "Lori", id: 23}];
var arr = []
for(var i in sheetData){
var someObject = sheetData[i];
arr.push(someObject[Object.keys(someObject)[0]]);
}
console.log(arr);
You have to move the return statement outside the loop.
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name),
sheetData = sheet.getDataRange().getValues(),
data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
data.push(obj);
}
return data;
}
I'm not sure what your intent is, but probably it should be something like this?
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
var obj = {};
obj = sheetData[i][0];
data.push(obj);
}
return data;
}
UPDATE
As #grogx noted below, creation of a temporary object appears unnecessary in this context and the sample above could be optimized to
function getSheetSectionData(name){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(name);
var sheetData = sheet.getDataRange().getValues();
var data = [];
for (var i = 0; i < sheetData.length; i++){
data.push(sheetData[i][0]);
}
return data;
}
Which can further be shortened to
function getSheetSectionData(name){
return SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName(name)
.getDataRange()
.getValues()
.map((e) => e[0]);
}
However, we do not really know, what the original intent of the OP was. It may be the case, that that temporary object was indeed required for some sort of intermediate transformation, which was striped out from the MCVE.

How to create an object/array from a key/value string made up with '/'

Take the following string:
/foo/1/bar/2/cat/bob
I need to parse this into an object or array which ends up being:
foo = 1
bar = 2
cat = bob
var sample = "/foo/1/bar/2/cat/bob".substring(1);
var finalObj = {};
var arr = sample.split('/');
for(var i=0;i<arr.length;i=i+2){
finalObj[arr[i]] = arr[i+1];
}
console.log(finalObj);
const str = '/foo/1/bar/2/cat/bob/test/'
const parts = str.split('/')
.filter(val => val !== '')
const obj = {}
for (let ii = 0; ii < parts.length; ii+=2) {
const key = parts[ii]
const value = parts[ii+1]
obj[key] = !isNaN(value) ? Number(value) : value
}
console.log(obj)
Regular expressions is the tool of choice for all kinds of parsing:
str = '/foo/1/bar/2/cat/bob'
obj = {};
str.replace(/(\w+)\/(\w+)/g, (...m) => obj[m[1]] = m[2]);
console.log(obj);
Just for the fun of it,
let str = "/foo/1/bar/2/cat/bob",
arr = str.split("/"),
obj = {};
arr.shift();
while (arr.length) obj[arr.shift()] = arr.shift();

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

Count in an array the number for each same value

My function is
var MyArray= [];
$('input:checked').each(function(index) {
MyArray= ($(this).attr('id') + ":" + $(this).val()).length;
});
My array is
Array [ "1:R1", "2:R2", "3:R3", "4:R1" ]
I would like to count the differents values and to get this object
Object {R1:2, R2:1, R3:1}
Instead of putting the values in an array and then get the values out of the array to process them and create an object, put them in the object to start with:
var map = {};
$('input:checked').each(function() {
var key = $(this).val();
if (key in map) {
map[key]++;
} else {
map[key] = 1;
}
});
Demo: http://jsfiddle.net/Guffa/0a35c6yp/
You can convert your var with this code :
var arr = [ "1:R1", "2:R2", "3:R3", "4:R1" ];
var obj = {};
for(var i=0, l=arr.length; i<l; i++) {
var parts = arr[i].split(':');
if(parts.length > 1) {
if(!obj[parts[1]]) {
obj[parts[1]] = 0;
}
obj[parts[1]]++
}
}
console.log(obj)
Or create directly the correct object :
var obj = {};
$('input:checked').each(function (index) {
var key = $(this).val();
if (!obj[key]) {
obj[key] = 0;
}
obj[key]++
});
Use a regex to capture the correct portion of the string, and add them as keys to the object, incrementing the value if it already exists:
var regex = /\d+:(R\d+)/
var obj = {};
arr.forEach(function (el) {
var key = el.match(regex)[1];
if (!obj[key]) obj[key] = 0;
obj[key]++;
});
DEMO
You could try something like that:
Write your Array into a Map and step up your value each time your map already knows the key.
for(var i = 0; i < myArray.length; i++){
var entry = myArray[i];
var key = entry.split(":")[1];
if(myMap.has(key))
myMap.set(key, myMap.get(key) + 1);
else
myMap.set(key, 1);
}
DEMO

Push an associative item into an array in JavaScript

How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle
To make something like associative array in JavaScript you have to use objects.
​
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
DEMO: http://jsfiddle.net/bz8pK/1/
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​
To get value you can use now different ways:
console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​
JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.
Another method for creating a JavaScript associative array
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];
If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.
// Order of entry altered
let obj = {}; // will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);
// Order of entry maintained for future iteration
obj = []; // will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

Categories

Resources