array object manipulation to create new object - javascript

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});
}
}

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 count the JSON object and on the basis of count take the same output

How to count the JSON object and on the basis of count take the same output
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
First I would like the count after it on the basis of count. I want same output like input.
for Count:-
var count = 0;
function getCount() {
for (var i = 0; i < obj.length; i++) {
count++;
}
return count;
}
for output :-
function showDetails() this is not giving the proper output
{
for(var j=0; j< count; j++){
obj.push([{j}]);
}
alert(obj.name);
}
alert(showDetails());
And I want an output like:-
var obj =
[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
];
Can anybody help me please?
var data ="January,February,March,April,May,June,July,August,September,October";
var obj = data.split(',').map((item)=>{
return {
name:item
}
});
obj will be the desired output
var str = "January,February,March,April,May,June,July,August,September,October";
var arr = str.split(',').map(function(v) {
return {name: v};
});
console.log(arr);
var str = "January,February,March,April,May,June,July,August,September,October";
var months = str.split(",");
var result = [];
for (i in months)
{
var month = {};
month.name = months[i];
//you can do more things else here, for example:
//month.monthOfYear = (i+1);
//month.numberOfDay = 123123123;
result.push(month);
}
You can do something like this:
var array = string.split(",");
var finalArray = [];
array.forEach(function(item){
var obj = {
name: item
}
finalArray.push(obj);
});
console.log(finalArray);
MDN reference
use var array = string.split(',');
For a more ES2015 heavy version. Constants, arrow function and implicit return statement.
const str = 'January,February,March,April,May,June,July,August,September,October'
const result = str.split(',').map(name => ({name}))
console.log(result)

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

Split array as per values in it

I have array like this
var aaa = [
[value1,value2],[0,0]],
[[value3,value4],[0,1]],
[[value5,value6],[1,0]],
[[value7,value8],[0,2]],
[[value9,value10],[1,1]],
[value11,value12],[2,0]]
];
I want to split this array into multiple arrays as per values [0,1], [0,2], etc.
I.e.
array1 = [[value1,value2],[value3,value4],[value7,value8]];
array2 = [[value5,value6],[value9,value10]];
array3 = [[value11,value12]];
How can I do this ?
Use this:
var aaa = [
[['value1','value2'],[0,1]],
[['value3','value4'],[0,2]],
[['value5','value6'],[1,0]],
[['value7','value8'],[0,3]],
[['value9','value10'],[1,1]],
[['value11','value12'],[2,0]]];
var result = {};
for (var i = 0; i < aaa.length; i += 1) {
if (!result[aaa[i][1][0]]) {
result[aaa[i][1][0]] = [];
}
result[aaa[i][1][0]].push(aaa[i][0]);
}
After that:
result[0]; //[[value1,value2],[value3,value4],[value7,value8]];
result[1]; //[[value5,value6],[value9,value10]];
result[2]; //[[value5,value6],[value9,value10]];
Supposing this :
[['value1','value2'],[0,1]]
In this example :
0 tell in which array the value must be stored.
1 tell in which cell of this array it must be stored.
This code would do the work :
var aaa = [
[['value1','value2'],[0,1]],
[['value3','value4'],[0,2]],
[['value5','value6'],[1,0]],
[['value7','value8'],[0,3]],
[['value9','value10'],[1,1]],
[['value11','value12'],[2,0]]
];
var arr_result = new Array();
for (var k in aaa) {
if (arr_result[aaa[k][1][0]] == undefined) {
arr_result[aaa[k][1][0]] = new Array();
}
arr_result[aaa[k][1][0]][aaa[k][1][1]] = aaa[k][0];
}
Warning : this could let empty cells, just as in this example, there is no [0,0] cell.

How to extract values from an array of arrays in Javascript?

I have a variable as follows:
var dataset = {
"towns": [
["Aladağ", "Adana", [35.4,37.5], [0]],
["Ceyhan", "Adana", [35.8,37], [0]],
["Feke", "Adana", [35.9,37.8], [0]]
]
};
The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?
var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data
And what to do if I want to store both values in the array? That is
var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data
I'm very new to Javascript. I hope there's a way without using for loops.
On newer browsers, you can use map, or forEach which would avoid using a for loop.
var myArray = dataset.towns.map(function(town){
return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]
But for loops are more compatible.
var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
myArray.push(dataset.towns[i][2];
}
Impossible without loops:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]
And what to do if I want to store both values in the array?
Similar, you just add the entire array, not only the first element:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]

Categories

Resources