I have a following array, which contains dates.
var arrs= ["2016/10/4", "2016/10/4", "2016/10/7", "2016/10/7", "2016/10/7"];
I am reducing this array to get count of same dates, so I am using following code,
var maps = arrs.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
console.log(maps);
Now, the count is available for each unique dates as follows in browser console,
Object {2016/10/4: 2, 2016/10/7: 3}
I want to make json object for this reduce object.
[{
date : 2016/10/4,
value : 2
},
{
date : 2016/10/7,
value : 3
}]
How to get it, I am not able to get length or make forEach to maps.
After generating the object use Object.keys and Array#map methods to generate the required array.
var arrs = ["2016/10/4", "2016/10/4", "2016/10/7", "2016/10/7", "2016/10/7"];
var maps = arrs.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
maps = Object.keys(maps) // get all property name
// iterate and generate eleemnt
.map(function(k) {
// generate prefered structure of array eleement
return {
date: k,
value: maps[k]
};
});
console.log(maps);
Related
I have the following json:
{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}
Currently I am trying to get its key-value with the below code:
var data = JSON.stringify(row);
var result = $.parseJSON(data);
$.each(result, function (k, v) {
//display the key and value pair
console.log(k, v);
});
The above code works fine and I can get my key-value from it.
Now what I am trying to get is the next key-value pairs within the $.each loop.
For example if in the loop the current key is "0" I want to get the next key "1" in the same call itself. If in the loop the current key is "1" I want to get the next key "$$hashKey" along with their values.
Is it possible to do so? I am open to code changes above if required.
You can use Object.keys to get the keys to an array, then run through it with a forEach to have access to the keys index. Important to note that objects are unordered, so your key order one time may differ from the next time:
var keys = Object.keys(obj);
keys.forEach(function(key, index) {
var nextIndex = index + 1;
if (nextIndex === keys.length) return; //out of bounds
var nextKey = keys[nextIndex];
});
Edit: As pointed out by the comments - if you want the keys in the same order each time, call .sort() on your keys array with your desired sort logic.
Understanding now that the goal is to retrieve keys in the order they appear in JSON, a couple of thoughts:
(1) if you control the source of the object ("row" in the OP code), don't represent it as an object. instead use an array of key-value pairs: [[0, "2"], [1, "2"], [$$hashKey, "object:35"], [undefined, "1"]].
otherwise, (2) roll your own JSON parser that returns an array of key-value pairs for an object. This post looks to be a sensible start. Or, you can vastly simplify the task if you are able to make certain assumptions about the values, for example, say you know that all values are strings...
// parse a string representing an object, returning an array of key-value pairs.
// assumes values are strings that do not contain commas or colons
function myProbablyNegligentlySimpleJSONParse(string) {
let trimmed = string.trim().slice(1, -1);
let components = trimmed.split(',');
return components.map(kvString => {
let kv = kvString.split(':');
return [ kv[0].trim(), kv[1].trim() ];
});
}
forEach passes the current index to the iterator function, so that int can be used to look ahead or behind in the iteration.
var data = '{0: "2", 1: "2", $$hashKey: "object:35", undefined: "1"}';
let result = myProbablyNegligentlySimpleJSONParse(data);
result.forEach(function (pair, index) {
let [k, v] = pair; // now k and v are your key and value
console.log(`key is ${k} value is ${v}`)
if (index < result.length-1) {
let [nextK, nextV] = result[index+1];
console.log(`next key is ${nextK} next value is ${nextV}`);
}
});
You could turn your object into an iterable and which will return the next [key, value] pair each time you call next on the iterator:
function makeIterable(o) {
o[Symbol.iterator] = () => {
var keys = Object.keys(o);
var i = 0;
return {
next() {
var done = false;
var value = [keys[i + 1], o[keys[i + 1]]];
if (i >= (keys.length - 1)) {
done = true;
}
i++;
return {
value,
done
}
}
};
}
}
var jsonStr = '{ "0": "2", "1": "2", "$$hashKey": "object:35", "undefined": "1" }';
var obj = JSON.parse(jsonStr);
makeIterable(obj);
var itr = obj[Symbol.iterator]();
while (true) {
var item = itr.next();
if (item.done) {
break;
}
console.log(item.value);
}
I am trying to use reduce() for getting economy rate for a particular wicket.
Example data:
var data = [
{wicket:0, econ:20 },
{wicket:1, econ:10 },
{wicket:3, econ:45 },
{wicket:0, econ:15 },
{wicket:1, econ:32 }
]
I want reduce() method to return an array of objects which will look like this:
0: 20, 15
1: 10, 32
3: 45
What I am trying to do is initialize accumulator with object but in reduce() method I am not able to figure out how can I get the required array of objects with key value as wicketand values as economy.
My code:
const Economy = data.reduce( (a, {econ, wicket}) => {
a[wicket].push(econ);
},{})
I get undefined behaviour with above code.
If your data was meant to be an Array and not an Object (which it isn't right now, at least not a valid one) :
let data = [
{wicket:0, econ:20 },
{wicket:1, econ:10 },
{wicket:3, econ:45 },
{wicket:0, econ:15 },
{wicket:1, econ:32 }
];
let result = data.reduce((acc, curr) => {
if(acc[curr.wicket]) acc[curr.wicket].push(curr.econ);
else acc[curr.wicket] = [curr.econ];
return acc;
},{});
console.log(result);
You can use group the array using reduce like:
var data = [{"wicket":0,"econ":20},{"wicket":1,"econ":10},{"wicket":3,"econ":45},{"wicket":0,"econ":15},{"wicket":1,"econ":32}];
var result = data.reduce((c, v) => {
c[v.wicket] = c[v.wicket] || []; //Initiate the property as empty array of it does not exist
c[v.wicket].push(v.econ);
return c;
}, {});
console.log(result);
|| is an OR operator.
This means if c[v.wicket] exist, it will assign it to c[v.wicket] again. If it does not, assign an empty array []
c[v.wicket] = c[v.wicket] || [];
I am trying to reduce a JSON array. Inside the array are other object, I am trying to turn the attributes into their own array.
Reduce Function:
// parsed.freight.items is path
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
return prevVal += currVal.item
},[])
console.log(resultsReduce);
// two items from the array
// 7205 00000
console.log(Array.isArray(resultsReduce));
// false
The reduce function is kind of working. It gets both item from the items array. However I am having a couple problems.
1) The reduce is not passing back an array. See isArray test
2) I am trying to make a function so I can loop through all of the attributes in the array the qty, units, weight, paint_eligable. I cannot pass a variable to the currVal.variable here
Attempting:
var itemAttribute = 'item';
var resultsReduce = parsed.freight.items.reduce(function(prevVal, currVal){
// pass param here so I can loop through
// what I actually want to do it create a function and
// loop through array of attributes
return prevVal += currVal.itemAttribute
},[])
JSON:
var request = {
"operation":"rate_request",
"assembled":true,
"terms":true,
"subtotal":15000.00,
"shipping_total":300.00,
"taxtotal":20.00,
"allocated_credit":20,
"accessorials":
{
"lift_gate_required":true,
"residential_delivery":true,
"custbodylimited_access":false
},
"freight":
{
"items":
// array to reduce
[{
"item":"7205",
"qty":10,
"units":10,
"weight":"19.0000",
"paint_eligible":false
},
{ "item":"1111",
"qty":10,
"units":10,
"weight":"19.0000",
"paint_eligible":false
}],
"total_items_count":10,
"total_weight":190.0},
"from_data":
{
"city":"Raleigh",
"country":"US",
"zip":"27604"},
"to_data":
{
"city":"Chicago",
"country":"US",
"zip":"60605"
}
}
Thanks in advance
You may need Array#map for getting an array of items
var resultsReduce = parsed.freight.items.reduce(function (array, object) {
return array.concat(object.item);
}, []);
The same with a given key, with bracket notation as property accessor
object.property
object["property"]
var key = 'item',
resultsReduce = parsed.freight.items.reduce(function (array, object) {
return array.concat(object[key]);
}, []);
Hey I have an object as
data = { vaibhavs:243 "132" ,
vaibhavs:918 "342",
karthikp:265 "345",
marimuthu:848 "asjkd",
ushas:918 "sdf15",
apoorvg:728 "wddfs"....
}
I need to sort it on the basis of key ,i.e., "vaibhavs:243" alphabatically.
I have written the following code for it. I am able to sort the keys, but not able to put it back in the returning object. Please guide what to do.
function sortData(data) {
var sorted = [];
Object.keys(data).sort(function (a, b) {
return a < b ? -1 : 1
}).forEach(function (key) {
var obj = {};
obj[key] = data[key]
sorted.push(obj);
});
return sorted;
}
This is giving me an array of object which i don't want. I want a single object.
I can't do this using an array because I need the sorted key-value pairs.
If I am using the following code,
function sortData(data) {
var sorted = {};
Object.keys(data).sort(function (a, b) {
return a < b ? -1 : 1
}).forEach(function (key) {
sorted[key] = key[data]
});
return sorted;
}
The above code is always overwriting the existing value. Can someone suggest me how to add the Key value pair. As I have that in sorted order, but just unable to add them in a single object.
if you are looking for Get/Delete/Sum/IsExist functions for an array of objects using javascript, I have posted this question and answer for such functions
Remove Object from an Array using JavaScript
Is Exist for an Object from an Array using JavaScript
Select Object from an Array using JavaScript
Sum Object values in an Array using JavaScript
How do I check if an array includes an object in JavaScript?
How do I remove a particular element from an array in JavaScript?
Find object by id in an array of JavaScript objects
summing numbers stored in an array in JavaScript, sum values of a javascript array?, Loop through array and return sum of all values
Btw, your question doesn't have much to do with JSON, and naught with jQuery.
Just use underscore.
Remove from a simple array:
var newList = _.without(list, 'hello', 'world'); // Remove any instance of 'hello' and 'world'
Remove from an array of objects:
var toRemove = _.where(list, {title: 'hello', subtitle: 'world'});
var newList = _.difference(list, toRemove);
Exists in array:
var exists = _.contains(list, value);
Get item from array:
var item = _.find(list, function(i){ i === value }); // For simple types
var item = _.findWhere(list, {title: 'hello', subtitle: 'world'}); // For complex types
Sum items:
var sum = _.reduce(list, function(start, num){ return start + num; }, 0);
And A LOT more.
4 Javascript Helpers
Remove Object from an Array using JavaScript
Is Exist for an Object from an Array using JavaScript
Select Object from an Array using JavaScript
Sum Object values in an Array using JavaScript
var JShelpers = {
removeItemFromArray: function (myObjects, prop, valu) {
return myObjects.filter(function (item) {
return item[prop] !== valu;
});
},
isExistInArray: function (myObjects, prop, valu) {
var i = myObjects.length;
while (i--) {
if (myObjects[i][prop] == valu) {
return true;
}
}
return false;
},
getItemFromArray: function (myObjects, prop, valu) {
var i = myObjects.length;
while (i--) {
if (myObjects[i][prop] == valu) {
return myObjects[i];
}
}
return "";
},
sumItemInArray: function (myObjects, prop) {
var summation = 0;
myObjects.forEach(function (item) {
summation += parseFloat(item[prop]);
});
return summation;
}
}
Example:
Say you have an array of Employees in a Json Format like this
var employeesArray = [{"Id":1,"Name":"tom","Age":15},{"Id":2,"Name":"Harry","Age":17}];
And you want to retrieve employee by his Age not only ID (as common) ,
you can simply call
JShelpers.getItemFromArray(employeesArray,"Age",15)