I got a json which looks like something like this :
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
For the moment I have something like that :
<script>
function myFunction() {
;
}
</script>
<div id = "short">
<button onclick="myFunction()">
short
</button>
</div>
My json is actually bigger than this example. I'd like to loop through it to get only the positions who are "short" and print them.
What is the best way to do that using only javascript ?
EDIT :
This is my new code but I still can't access to short or long position :
var stocks = [];
var longOnMarket = [];
var shortOnMarket = [];
var typeOfPosition = [];
var lolz = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
lolz.push(JSON.stringify(item));
stocks.push(key);
var json2 = json[item];
for (var key2 in json2) {
if (json2.hasOwnProperty(key2)) {
var longOrShort = json2[key2].positions;
typeOfPosition.push(JSON.stringify(longOrShort));
}
}
}
}
alert(stocks);
alert(lolz);
alert(typeOfPosition);
What you can do is
var json = {
"stock1" : {
"positions" : [{
"date": "29/02/2016",
"price": 15,
"type": "short"
}]
},
"stock2" : {
"positions" : [{
"date": "29/02/2016",
"price": 20,
"type": "long"
}]
}
};
var object = JSON.parse(json);
for (var key in object) {
//Do your stuff
}
This solution looks for the array of positions and returns the object if some short is found.
var object = { "stock1": { "positions": [{ "date": "29/02/2016", "price": 15, "type": "short" }] }, "stock2": { "positions": [{ "date": "29/02/2016", "price": 20, "type": "long" }] } },
short = {};
Object.keys(object).forEach(function (k) {
if (object[k].positions.some(function (a) { return a.type === 'short' })) {
short[k] = object[k];
}
});
document.write('<pre>' + JSON.stringify(short, 0, 4) + '</pre>');
You should simple iterate through your object keys
var result = [];
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
item.positions = item.positions.filter(function(el) { return el.type == 'short' });
result.push(item);
}
}
here is my try please check it out
var i,
shortTypePositionsArray = [],
shortTypeWholeObject = {};
$.each(json,function(key,value){
if(Object.keys(value) == "positions"){
for(i = 0;i<value.positions.length;i++){
if(value.positions[i].type == 'short')
{
shortTypePositionsArray.push(value.positions[i]);
shortTypeWholeObject[key] = value;
}
}
}
});
console.log(shortTypePositionsArray);
console.log(shortTypeWholeObject);
Related
I have an array this the format below. Trying to push multiple entire subarrays (starting with A-) fulfilling a condition to a new array and keep the array format. Have no success with the code below.
Array:
{"#VER": {
"A-1": {
"verdatum": "2016-07-08",
"vertext": "1073, Almi",
"trans": [{
"account": "1510",
"amount": "52500.00"
}, {
"account": "3010",
"amount": "-42000.00"
}, {
"account": "2611",
"amount": "-10500.00"
}]
},
"A-2": {
"verdatum": "2016-07-08",
"vertext": "1074, Text",
"trans": [{
"account": "1510",
"amount": "15000.00"
}, {
"account": "3010",
"amount": "-12000.00"
}, {
"account": "2611",
"amount": "-3000.00"
}]
}
}
}
Code so far, but changes format of array
var newarray = [];
$.each(array["#VER"], function(i, item) {
if (condition for subarray) {
newarray.push(i,item);
}
});
You're working with an object here, not an array. This code should work:
var data = { ... }; // your original data object
var filteredData = filterData(data);
function filterData(data) {
var verData = data['#VER'];
var filteredVerData = {};
$.each(verData, function(key, value) {
if(value.vertext === '1073, Almi') { // your condition
filteredVerData[key] = value;
}
});
return {
'#VER': filteredVerData
};
}
But if you have many root keys like '#VER' and you need to filter all of them, you'd need to write one more loop:
var data = { ... }; // your original data object
var filteredData = filterData(data);
function filterData(data) {
var result = {};
$.each(data, function(verKey, verData) {
$.each(verData, function(aKey, aData) {
if(aData.vertext === '1073, Almi') { // your condition
result[verKey] = result[verKey] || {};
result[verKey][aKey] = aData;
}
});
});
return result;
}
How do I push an object into an specified array that only updates that array? My code pushes an object and updates all arrays, not just the specified one.
Here is the structure of the data:
{
"d": {
"results": [
{
"Id": 1,
"cost": "3",
"item": "Project 1",
"fiscalyear": "2014",
"reportmonth": "July"
}
]
}
}
Here is a sample of the desired, wanted results:
{
"Project 1": [
{
"date": "31-Jul-14",
"rating": "3"
},
{
"date": "31-Aug-14",
"rating": "4"
}
],
"Project 2": [
{
"date": "31-Jul-14",
"rating": "2"
}
]
}
This is my attempt:
var results = data.d.results;
var date;
var projectObj = {},
projectValues = {},
project = '';
var cost = '',
costStatus = '';
for (var i = 0, m = results.length; i < m; ++i) {
project = results[i]['item'];
if (!projectObj.hasOwnProperty(project)) {
projectObj[project] = [];
}
// use Moment to get and format date
date = moment(new Date(results[i]['reportmonth'] + ' 1,' + results[i]['fiscalyear'])).endOf('month').format('DD-MMM-YYYY');
// get cost for each unique project
costStatus = results[i]['cost'];
if (costStatus == null || costStatus == 'N/A') {
cost = 'N/A';
}
else {
cost = costStatus;
}
projectValues['rating'] = cost;
projectValues['date'] = date;
projectObj[project].push(projectValues);
}
Here is a Fiddle with the undesired, unwanted results:
https://jsfiddle.net/yh2134jn/4/
What am I doing wrong?
That is because You do not empty it new iteration. Try this:
for (var i = 0, m = results.length; i < m; ++i) {
projectValues = {};
project = results[i]['item'];
....
}
[{
"name":"John"
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
John have 2 hobbies, it suppose to be in array but I have no control of the source of the api. How can I make the json to be below format?
[{
"name":"John"
"age":19,
"hobby":"Basketball"
},{
"name":"John"
"age":19,
"hobby":"play computer"
},
{
"name":"Anderson"
"age":19,
"hobby":"Tennis"
}
]
I'm new to jquery so here's code I've tried :
var hobbies = "";
$.each(json, function(){
hobbies = this.hobby.split(',');
});
var data = [{
"name": "John",
"age": 19,
"hobby": "Basketball;play computer"
}, {
"name": "Anderson",
"age": 19,
"hobby": "Tennis"
}]
$.each(data, function (index, value) {
if (value.hobby.split(';').length > 1) {
var dataArray = value.hobby.split(';');
value.hobby = dataArray[0];
dataArray.shift();
$.each(dataArray, function (innerIndex, innerValue) {
data.push({
"name": value.name,
"age": value.age,
"hobby": innerValue
});
});
}
});
console.log(data);
Fiddle Demo
var arr = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$.each(arr, function(i,j){
var temp = j.hobby;
var hobby_arr = temp.split(';');
j.hobby = hobby_arr;
});
Try this. However there is an error in your provided json. There should be a ',' after the 'name' value
Here is a fiddle of your working thing ( assuming that ";" is the separator )
http://jsfiddle.net/swaprks/vcpq8dtr/
var json = [{
"name":"John",
"age":19,
"hobby":"Basketball;play computer"
},
{
"name":"Anderson",
"age":19,
"hobby":"Tennis"
}
];
$(function(){
for ( var i = 0; i < json.length; i++ ) {
var obj = json[i];
if ( obj["hobby"].indexOf(";") != -1 ){
var hobbyArr = obj["hobby"].split(";");
for ( var j = 0; j < hobbyArr.length; j++ ){
var newObj = {};
if ( j == 0 ){
json[i]["hobby"] = hobbyArr[j];
} else {
newObj = {
"name": obj["name"],
"age": obj["age"],
"hobby": hobbyArr[j]
}
json.push(newObj);
}
}
}
}
console.log(json)
});
I'm trying to remove obects from an object if they appear in other objects. Really hard to exaplin! Here's an example. I have 2 Objects containing DOM image objects and I would like the DOM image objects removed from the first object if they appear in the second object.
First Object
{
"241": [{
"img": image_object_1
},
{
"img": image_object_2
},
{
"img": image_object_3
},
{
"img": image_object_4
}]
}
Second Object
{
"241": [{
"img": image_object_1
},
{
"img": image_object_3
},
{
"img": image_object_4
}]
}
Expected result of object 1
{
"241": [{
"img": image_object_2
}]
}
I have everything in a single object like so but I'm happy to change the format if needs be
{
"0": {
},
"1": {
"241.14999389648438": [{
"img": {
image_object_1
},
},
{
"img": {
image_object_2
},
},
{
"img": {
image_object_3
},
},
{
"img": {
image_object_4
},
}]
},
"2": {
"241.14999389648438": [{
"img": {
image_object_2
},
},
{
"img": {
image_object_3
},
},
{
"img": {
image_object_4
},
}]
}
}
My working code is here
jQuery.fn.reverse = [].reverse;
function same_height(){
var imob = {};
var groups = [];
var heights = [];
var tp = 0;
var img = false;
$("#ez-container .row").each(function(gi){
imob = {};
groups[gi] = {};
heights[gi] = {};
tp = 0;
img = false;
$(this).find(".ez-image img").each(function(){
img = $(this);
tp = img.offset().top;
imob = {
"img":img,
"padding":img.outerHeight(true) - (parseInt(img.css('borderBottomWidth'))+parseInt(img.css('borderTopWidth'))) - img.innerHeight()
};
if(typeof(groups[gi][tp])=="undefined"){
groups[gi][tp] = [];
heights[gi][tp] = [];
}
groups[gi][tp].push(imob);
heights[gi][tp].push(img.height());
});
});
heights.reverse();
var max_group_height = 0;
$.each(groups.reverse(),function(gix,grp){
$.each(grp,function(t,im){
if(im.length>1){
$.each(im,function(i,v){
max_group_height = Math.max.apply(Math, heights[gix][t]);
if(typeof(v.img.attr("data-fixed"))=="undefined"){
v.img.css({"height":max_group_height+(v.padding)+"px"}).attr("data-height",0).attr("data-width",0).attr("data-fixed",1);
}
});
}
});
});
do_swap_images();
}
if you checking dom image node, you need isSameNode functions. I am not sure about your requirements, hope below code will helps
//suppose a, b are your objects
var key = 241
var diff = a[key].filter( function( v ){
var firstImgNode = v.img;
return !b[key].some( function( v ){
return v.img.isSameNode( firstImgNode );
});
});
or if you checking other data type, then simply do v.img == firstImgNode
I am working on application which I need to do grouping of different sets of javascript object and those will be based on month,day and year.
For day I am doing like below
var calculateByDay = function(inputList){
var outPutList = [];
var result = {}
var item = null, key = null;
for(i=0; c<inputList.length; i++) {
item=inputList[c];
key = Object.keys(item)[0];
item=item[key];
if(!result[key]) {
result[key] = item;
}
else {
result[key] += item;
}
for (r in result)
{
var docs = {};
docs["date"] = r;
docs["amount"] = result[r];
outPutList.push(docs);
}
}
return outPutList;
}
How can I improve above code and use it for month and year calculation also?
I went thorough underscore.js and it has a groupBy method. but seems not fits with my requirement.
I want to group by months and year also,
for
var inputList = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
The output should be:
Monthly :
[{"December 2012": 2000}, {"January 2013": 1200},{"February 2013": 1550}];
Yearly
[{"year 2012": 2000}, {"year 2013": 2750}];
And it seems I need to this kind of map,reduce approach for large data(array sets), is there any other library or practices I can do to make the code solid?
Thanks in advance.
Given a slightly different structure of data:
var data = [{
"date": "2011-12-02T00:00",
"value": 1000
}, {
"date": "2013-03-02T00:00",
"value": 1000
}, {
"date": "2013-03-02T00:00",
"value": 500
}, {
"date": "2012-12-02T00:00",
"value": 200
}, {
"date": "2013-04-02T00:00",
"value": 200
}, {
"date": "2013-04-02T00:00",
"value": 500
}, {
"date": "2013-03-02T00:00",
"value": 500
}, {
"date": "2013-04-12T00:00",
"value": 1000
}, {
"date": "2012-11-02T00:00",
"value": 600
}];
You could use underscore:
var grouped = _.groupBy(data, function(item) {
return item.date;
});
var groupedByYear = _.groupBy(data, function(item) {
return item.date.substring(0,4);
});
var groupedByMonth = _.groupBy(data, function(item) {
return item.date.substring(0,7);
});
console.log(groupedByYear);
See related answer: Javascript - underscorejs map reduce groupby based on date
Please see if the following refactor is useful for you
http://jsfiddle.net/wkUJC/
var dates = [{"2012-12-02T00:00": 2000}, {"2013-01-01T00:00": 1200},{"2013-02-02T00:00": 550}, {"2013-02-02T00:00": 1000}];
function calc(dates) {
var response = {};
dates.forEach(function(d){
for (var k in d) {
var _ = k.split("-");
var year = _[0]
var month = _[1]
if (!response[year]) response[year] = {total: 0}
response[year][month] = response[year][month] ? response[year][month]+d[k] : d[k]
response[year].total+= d[k]
}
});
console.log(response);
return response;
}
calc(dates);