Adding values contained in an array of objects - javascript

How would I go about adding all the values within the object?
For example amoutpay": ["4222","1000"] would give me 5222
This is my object:
{
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
}
What I want is to add the values to variables. Would I use split?
var a =
var b =
var c =

You can use Array.prototype.reduce() as shown below:
var obj = {
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
},
a = obj.amoutpay.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
}),
b = obj.amtpending.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
}),
c = obj.totalcost.reduce(function(prevVal, curVal, curInd) {
return +prevVal + +curVal;
});
console.log( a, b, c );
Or you could go a step further and define your own array method, eg Array.prototype.sum():
var obj = {
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
};
Array.prototype.sum = function() {
return this.reduce(function( prv, cur, ind ) {
return +prv + +cur;
});
};
var a = obj.amoutpay.sum(),
b = obj.amtpending.sum(),
c = obj.totalcost.sum();
console.log( a, b, c );

var obj = {
"amoutpay": [ "4222", "1000" ],
"amtpending": [ "778", "4000" ],
"totalcost": [ "5000", "5000" ],
"coursename": [ "Office Automation", "ajaba" ]
}
var a = addValues(obj.amoutpay);
function addValues(arr) {
return arr.map(function(el) {
return Number(el);
}).reduce(function(prev, curr){
return prev + curr;
})
}

We iterate the object elements and for all arrays we check whether all the elements are numeric. If so, then add them as variables to the window object, so after the loop we will have an amoutpay variable for the input shown in the question. Note, that if a key happens to already be a variable, then this code will override it.
for (var key in obj) {
if (Array.isArray(obj[key])) {
var shouldAdd = true;
for (var index = 0; shouldAdd && index < obj[key].length; index++) {
if (isNaN(obj[key][index])) {
shouldAdd = false;
}
}
if (shouldAdd) {
window[key] = 0;
for (var index = 0; index < obj[key].length; index++) {
window[key] += parseFloat(obj[key][index]);
}
}
}
}

Related

How to generate a function that, having the array above as input parameter, generates the following output?

given the following array:
[['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']]
(where the internal array will always have team, dependency, tickets)
• Generate a function that, having the above array as input parameter, generates the following output:
[
{
"dependencies": [
{
"name": "dep1",
"tickets": [
{
"name": "tkt1"
}
]
}
],
"name": "team1"
},
{
"dependencies": [
{
"name": "dep1",
"tickets": [
{
"name": "tkt2"
},
{
"name": "tkt10"
}
]
},
{
"name": "dep3",
"tickets": [
{
"name": "tkt75"
}
]
}
],
"name": "team2"
}
]
You can do something like this
const input = [
["team1", "dep1", "tkt1"],
["team2", "dep1", "tkt2"],
["team2", "dep3", "tkt75"],
["team2", "dep1", "tkt10"],
];
const transform = (data) => {
const teamDepMap = {};
data.forEach(([team, dep, ticket]) => {
if (!teamDepMap[team]) {
teamDepMap[team] = {};
}
if (!teamDepMap[team][dep]) {
teamDepMap[team][dep] = [{name: ticket}];
} else {
teamDepMap[team][dep].push({name: ticket});
}
});
return Object.entries(teamDepMap).map(([team, dependencyMap]) => ({
name: team,
dependencies: Object.entries(dependencyMap).map(([dependency, tickets]) => ({
name: dependency,
tickets
}))
}))
}
console.log(transform(input));
const objectb = [];
function Convertarray(list){
for (let i = 0, len = list.length; i < len; i++) {
let c ={
"dependencies": [
{
"name": list[i][1],
"tickets": [
{
"name": list[i][2]
}
]
}
],
"name": list[i][0]
}
objectb.push(c)
}
return objectb
}
let test=new Convertarray([['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']])
console.log(test);
const objectb = [];
function Convertarray(list){
for (let i = 0, len = list.length; i < len; i++) {
let c ={
"dependencies": [
{
"name": list[i][1],
"tickets": [
{
"name": list[i][2]
}
]
}
],
"name": list[i][0]
}
objectb.push(c)
}
return objectb
}
let test=new Convertarray([['team1','dep1','tkt1'], ['team2','dep1','tkt2'], ['team2','dep3','tkt75'], ['team2','dep1','tkt10']])
console.log(test);
let myString = JSON.stringify(test);
document.getElementById("result").innerHTML = myString;
<span id="result"></span>

Javascript manipulating json issue

[
{
"timing": [
{
"zone": 18.8
},
{
"zone": 17.06,
},
{
"zone": 16.6
},
]
},
{
"timing": [
{
"zone": 12.6,
},
{
"zone": 14.6,
}
]
},
{
"timing": [
{
"zone":19.06,
},{
"zone": 8.06,
}
]
}
]
Here i am trying to work manipulate with one json data using javascript.
But, I am not able to think any approach how to achive that.
I am expecting below json. It give zone1, zone2, zone3 as per the zone any it will be dynamically
Please have a look to below json.
[
{
"zone1": [18.8, 12.6, 19.06 ]
},{
"zone2": [17.06, 14.6, 8.06]
}, {
"zone3":[16.6]
}
]
This is the output of json how it should look like.
Please have a look
You can use reduce and forEach
Loop through data, set OP's initial value as an object
Loop through timing property of each element, check if the zone + index + 1 exists in op or not, if exists push zone to that key else initialise new key
let data = [{"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone": 19.06,}, {"zone": 8.06,}]}]
let final = data.reduce((op, { timing }) => {
timing.forEach(({ zone }, i) => {
let key = `zone${ 1 + i }`
op[key] = op[key] || []
op[key].push(zone)
})
return op
}, {})
console.log(final)
// If you need final output to be array of object just use entries and map to build a desired output
console.log(Object.entries(final).map(([k,v])=>({[k]:v})))
Here's a possible solution
var data = [{
"timing": [{
"zone": 18.8
},
{
"zone": 17.06,
},
{
"zone": 16.6
},
]
},
{
"timing": [{
"zone": 12.6,
},
{
"zone": 14.6,
}
]
},
{
"timing": [{
"zone": 19.06,
}, {
"zone": 8.06,
}]
}
];
// Calculate the total number of zones
var totalZones = 0;
for (let i = 0; i < data.length; i++) {
const currZones = data[i].timing.length;
if (currZones > totalZones) totalZones = currZones;
}
console.log(totalZones);
// Create the final Array
var result = new Array(totalZones);
for (let i = 0; i < totalZones; i++) {
result[i] = {
zone: []
}
}
// Populate the final array with values
for (let i = 0; i < totalZones; i++) {
for (let j = 0; j < data.length; j++) {
let currTiming = data[j].timing[i];
if (currTiming !== undefined) {
let currZone = data[j].timing[i].zone;
if (currZone !== undefined) {
result[i].zone.push(currZone);
}
}
}
}
console.log(result);
1) Gather all zone values into one array of array
2) Calculate max rows needed for zones
3) Have a simple for-loop till max rows and use shift and push methods.
const data = [
{
timing: [
{
zone: 18.8
},
{
zone: 17.06
},
{
zone: 16.6
}
]
},
{
timing: [
{
zone: 12.6
},
{
zone: 14.6
}
]
},
{
timing: [
{
zone: 19.06
},
{
zone: 8.06
}
]
}
];
const zones = data.map(time => time.timing.map(z => z.zone));
const rows = zones.reduce((rows, arr) => Math.max(rows, arr.length), 0);
const all = [];
for (let index = 1; index <= rows; index++) {
const res = [];
zones.forEach(zone => zone.length > 0 && res.push(zone.shift()));
all.push({ [`zone${index}`]: res });
}
console.log(all);
const input = [ {"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone":19.06,},{"zone": 8.06,}]}]
var data = input.map(t => t.timing.map(u => u.zone));
var output = data[0].map((col, i) => data.map(row => row[i])).map((item, index) => {res = {}; res["zone"+(index+1)] = item.filter(t => t!==undefined); return res});
console.log(output);
Not the shortest, but it's very readable.
var json = [{"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone": 19.06,}, {"zone": 8.06,}]}];
// index 0 is zone1, index 1 is zone2, index 2 is zone3, and so on ...
var zones = [];
// Loop through each 'timing' object
json.forEach(function(timingObject) {
var timing = timingObject['timing'];
// loop through each 'zone' in the given 'timing' object
timing.forEach(function(zoneObject, index) {
var zone = zoneObject['zone'];
// if the zone exists in the zones[] defined above
// add the current zone to its place
//
// if not (else), we have to add the array for the
// current index, then add the value of the current zone.
if(zones[index]) {
zones[index]['zone' + (index + 1)].push(zone);
} else {
zones.push({ ['zone' + (index + 1)]: [zone]})
}
});
});
console.log(zones);

How to Make a JSON from two string arrays - 1st array having values & 2nd array having ids in same sequence

Array 1 = Accessories:Bracket,Accessories:Clamp,Actuator:Accessories,Actuator:Accessories:Bracket,Actuator:Accessories:Clamp,Actuator:Clevis
Array 2 = 24092859,24092784,24094450,24094451,24110219,24092811
Required Output =
[
{
"text": "Accessories",
"children": [
{
"text": "Bracket",
"children": [],
"mtdtId": "24092859"
},
{
"text": "Clamp",
"children": [],
"mtdtId": "24092784"
}
],
"mtdtId": "24092859,24092784"
},
{
"text": "Actuator",
"children": [
{
"text": "Accessories",
"children": [
{
"text": "Bracket",
"children": [],
"mtdtId": "24094451"
},
{
"text": "Clamp",
"children": [],
"mtdtId": "24110219"
}
],
"mtdtId": "24110219,24094451"
},
{
"text": "Clevis",
"children": [],
"mtdtId": ""
}
],
"mtdtId": "24110219,24094451"
}
]
the parent should contain the id's of the child nodes.
const array1 = "Accessories:Bracket,Accessories:Clamp,Actuator:Accessories,Actuator:Accessories:Bracket,Actuator:Accessories:Clamp,Actuator:Clevis".split(
","
);
const array2 = "24092859,24092784,24094450,24094451,24110219,24092811".split(
","
);
const output = array1.reduce(
(topLevelNodes, path, i) => {
let nodes = topLevelNodes;
let mtdId = array2[i];
path.split(":").forEach(text => {
let node = nodes.filter(child => child.text === text)[0];
if (node) {
node.mtdId += "," + mtdId;
} else {
nodes.push((node = { text, children: [], mtdId }));
}
nodes = node.children;
});
return topLevelNodes;
},
[]
);
console.log(output);
You could use a hash table for the nested elements and get later all values of mtdtId for grouping of the children elements. I suggest to use a different property for the collection.
var array1 = 'Engines:Combustion,Engines:Combustion:AeroThermal,Engines:Combustion:Fuel Systems,Engines:Combustion:Mechanical,Engines:Fans & Compressors,Engines:Fans & Compressors:Centrifugal Compressor Aero'.split(','),
array2 = '001,002,003,004,005,006'.split(','),
result = [];
array1.forEach(function (a, i) {
a.split(':').reduce(function (r, k, j, kk) {
if (!r[k]) {
r[k] = { _: [] };
r._.push(j + 1 === kk.length ? { text: k, mtdtId: array2[i], children: r[k]._ } : { text: k, children: r[k]._ });
}
return r[k];
}, this);
}, { _: result });
result.reduce(function iter(r, a) {
var temp = a.mtdtId ? [a.mtdtId] : [];
if (Array.isArray(a.children)) {
temp = a.children.reduce(iter, temp);
}
if (a.mtdtId !== temp.join()) {
a.collected = temp.join();
}
return r.concat(temp);
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript: Convert JSON Array to Cascaded JSON

I have this simple JSON array structure
[
[ "1000", "Kangar","Perlis" ],
[ "1532", "Kangar", "Perlis" ],
[ "2000", "Kuala Perlis", "Perlis" ],
[ "6250", "Alor Setar", "Kedah" ],
[ "6300", "Kuala Nerang", "Kedah" ]
]
Now i want to structure the JSON like this
{
"Perlis":
{
"Kangar": [ "1000", "1532" ],
"Kuala Perlis": [ "2000" ]
},
"Kedah":
{
"Alor Setar":["6250"],
"Kuala Nerang":["2000"]
}
}
So how can i achieve this result using Javascript's object?
Try following
var arr = [
["1000", "Kangar", "Perlis"],
["1532", "Kangar", "Perlis"],
["2000", "Kuala Perlis", "Perlis"],
["6250", "Alor Setar", "Kedah"],
["6300", "Kuala Nerang", "Kedah"]
];
var obj = {};
arr.forEach(function(item) {
obj[item[2]] = obj[item[2]] || {};
obj[item[2]][item[1]] = obj[item[2]][item[1]] || [];
obj[item[2]][item[1]].push(item[0]);
});
console.log(obj);
You can use reduce to create the hash object like this:
function transform(arr) {
return arr.reduce(function(hash, sub) {
if(hash [sub[2]]) { // if we hashed the first-level-categry (sub[2])
if(hash [sub[2]] [sub[1]]) // -- if we hashed the second-level category (sub[1])
hash [sub[2]] [sub[1]].push(sub[0]); // ---- add the item (sub[0]) to that array
else // -- otherwise
hash [sub[2]] [sub[1]] = [sub[0]]; // ---- create second-level-category placeholder (new array) that initially contains the current item (sub[0])
}
else { // else
hash [sub[2]] = {}; // -- create the first-level-category placeholder
hash [sub[2]] [sub[1]] = [sub[0]]; // -- create the second-level-category placeholder (new array) that initially contains the current item (sub[0])
}
return hash;
}, {});
}
var array = [
["1000","Kangar","Perlis"],
["1532","Kangar","Perlis"],
["2000","Kuala Perlis","Perlis"],
["6250","Alor Setar","Kedah"],
["6300","Kuala Nerang","Kedah"]
];
console.log(transform(array));
var inputArr = [
["1000","Kangar","Perlis"],
["1532","Kangar","Perlis"],
["2000","Kuala Perlis","Perlis"],
["6250","Alor Setar","Kedah"],
["6300","Kuala Nerang","Kedah"]
];
var processFunction = function(arr){
var outputObj = {};
arr.forEach( function(elem){
if( !outputObj[ elem[2] ] )
outputObj[ elem[2] ] ={};
if( !outputObj[ elem[2] ] [ elem[1] ])
outputObj[ elem[2] ][ elem[1] ] = [];
outputObj[ elem[2] ][ elem[1] ].push( elem[0] );
});
return outputObj;
};
alert(JSON.stringify(processFunction(inputArr)) );
var arr = [
["1000", "Kangar", "Perlis"],
["1532", "Kangar", "Perlis"],
["2000", "Kuala Perlis", "Perlis"],
["6250", "Alor Setar", "Kedah"],
["6300", "Kuala Nerang", "Kedah"]
]
function convert(arr) {
return arr.reduce(function (o, e) {
o[e[2]] = o[e[2]] || {};
o[e[2]][e[1]] = o[e[2]][e[1]] || [];
o[e[2]][e[1]].push(e[0]);
return o;
}, {});
}
console.log(convert(arr));
What this o[e[2]] = o[e[2]] || {} does is it sets o[e[2]] to itself, or if it's a falsy value (like undefined) - to a new object. This acts as an easy initialization and prevents accessing non-existent values.
To be safe, you can add a check for each array element's length:
return arr.reduce(function(o, e) {
if (e.length === 3) {
...
}
return o;
}, {});
You can do this with reduce().
var data = [
["1000", "Kangar", "Perlis"],
["1532", "Kangar", "Perlis"],
["2000", "Kuala Perlis", "Perlis"],
["6250", "Alor Setar", "Kedah"],
["6300", "Kuala Nerang", "Kedah"]
]
var o = {}
var result = data.reduce(function(r, e) {
if (!o[e[1]]) {
o[e[1]] = {[e[1]]: []}
r[e[2]] = Object.assign((r[e[2]] || {}), o[e[1]])
}
o[e[1]][e[1]].push(e[0])
return r
}, {})
console.log(result)

Javascript or Ruby. Reformat a JSON object

I need to turn this JSON object:
[
[
"email#email.com"
],
[
"email2#email.com"
],
[
"email3#email.com"
],
[
"email4#email.com"
]
]
Into this:
{
"data": [
{
"email": "email#email.com"
},
{
"email": "email2#email.com"
},
{
"email": "email3#email.com"
},
{
"email": "email4#email.com"
}
] }
How is this done?
Well, that's really just an array of arrays, but that's besides the point. Just loop through the array of arrays and push the relevant data onto the new array in your object:
var my_new_object = {};
my_new_object['data'] = [];
for (var i = 0; i < your_array.length; i++) {
my_new_object.data.push({"email": your_array[i][0]});
}
Working demo.
Javascript:
var original = [
[
"email#email.com"
],
[
"email2#email.com"
],
[
"email3#email.com"
],
[
"email4#email.com"
]
];
var output = {};
output.data = new Array();
for(var i=0;i<original.length;i++){
var o = new Object();
o.email = original[i][0];
output.data.push(o);
}
you can test it here:
http://jsfiddle.net/v3fnk/
var data=[["email#email.com"],["email2#email.com"],["email3#email.com"],["email4#email.com"]];
for (var i in data) {
for (var x in data[i]) {
$("#info").append(data[i][x] + '<br/>');
}
}

Categories