how to create JavaScript object using a for loop? - javascript

i have an object sample data:
[Object, Object, Object]
0: Object
test_id: "1"
area: "high"
1: Object
test_id: "1"
area: "saw"
2: Object
test_id: "2"
area: "look"
i am trying to create a new object by grouping by test_id.
var obj = new Object();
$.each(data, function(k, v){
obj[v.test_id] += {area: v.area};
});
this doesn't seem to work, it returns only one object line...
i am trying to get something like:
1: {
{area: "high"}
{area: "saw"}
}
2: {
{area: "look""
}
any ideas? thanks

After your edit I notice something, you're trying to create a javascript object with a property with no name, this is not the format. In JSON (javascript object notation) each property must have a value, what you are trying to store better fits an array.
Instead, push it into an array
$.each(data, function(k, v){
obj[v.test_id].area.push(v.area);
});
just remember to create obj[v.test_id] first and to set its area property to [].
This results in:
1: {
area: ["high","saw"]
}
3: {
area: ["look"]
}
Also, if you're willing to consider using underscore it has very powerful (yet basic) collection methods, you might want to have a look at http://underscorejs.org/#groupBy

Related

How to iterate through array of objects and stringify

I've been at this for a bit trying to come up with a solution. I have tested a handful of stack solutions to iterate through nested objects but haven't gotten this to work correctly. My data structure is below.
I've been trying to first off iterate through nested objects which this stack seemed to be similar to mine.
Iterate through Nested JavaScript Objects
However, when I'm in my for loop getting access to geo, value object to grab all of its properties, ip, hostname, city etc I'm coming up empty handed with undefined. Here's a code snippet of what I've tried below.
I'm trying to take all of the keys and values in this entire object and stringify them into a beautiful parameter string to send over to the server in an ajax request.
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
o.value.ip;
}
}
0: {name: "firstname", value: "John"}
1: {name: "lastname", value: "Smith"}
2: {name: "email", value: "asddas#gmail.com"}
3: {name: "password", value: "asdsdadasads"}
4: {name: "paypal_email", value: "asdsa#gmail.com"}
5: {name: "phone", value: "1234567894"}
6: {name: "geo",value: "
{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
__proto__: Object
length: 7
__proto__: Array(0)
The problem is that the structure of the geo object is odd:
name: "geo",value: "{"ip":"111.111.111.111","hostname":"rr.com","city":"MyCity","region":"Ohio","country":"US","loc":"41.34.23","org":"Inc","postal":"1234","timezone":"America/New_York","readme":"https://www.google.com"}"
The value looks to be a string in JSON notation. You'll have to parse it first in order to look up properties on it:
if (o.name === "geo") {
const nestedObj = JSON.parse(o.value);
console.log(nestedObj.ip);
}
You might also consider fixing whatever's serving you that object so that the value is an actual object - if that's possible (it may not be, but it would make the code make a lot more sense).
You can also consider using .find instead of a for loop, to make the code shorter and more elegant:
const json = myarray.find(({ name }) => name === 'geo').value;
const nestedObj = JSON.parse(json);
(if the geo object may not exist, test for undefined first, of course)
It would appear that the value field for the object with the name of "geo" is a JSON string.
Because the value is a string, you won't be able to directly access the ip field without first parsing that string to an object:
for (var i = 0; i < myarray.length; i++) {
var o = myarray[i];
if (o.name === "geo") {
/* "Convert" the JSON string in o.value to the corresponding object */
const valueObject = JSON.parse(o.value);
/* The ip field can now be accessed from the valueObject, parsed from
the JSON string in o.value */
console.log(valueObject.ip);
}
}

CSV to JSON using D3.JS

I have a csv file in the following format
type,1,2,3,4,5,6,7,8,.... // Upto 48
type1,54.69801915,84.4717406,81.87766667,66.48516667,...
type2,51.57399106,84.23170179,82.13950136,67.37540461,...
......
I wanna draw a line chart using this csv data with d3. Once I nest them using below code
d3.nest().key(function(d) {
return d.type;
}).entries(data);
My json looks as follow
{ key: "type1", values: […] }
and inside values it is just a single element array and the value of that is { 1: 54.69801915, 2: 84.4717406, 3: 81.87766667, … }
But my expectation is that that would be a array something similar to
{ { 1: 54.69801915}, {2: 84.4717406}, {3: 81.87766667}, … }
Can someone tell me what I am doing wrong here? Or how should I get my expected format?
Well, that's the expected behaviour of d3.nest().
If you want that structure you shared in your question, with values as an array of objects, I suggest you write your own nesting function.
Here is an example of code that does what you want, using map and for...in. It's neither elegant nor beautiful, it's purposely verbose to be easily understood (I'm using only a few columns and rows in your data):
var csv = `type,1,2,3,4
type1,54.69801915,84.4717406,81.87766667,66.48516667
type2,51.57399106,84.23170179,82.13950136,67.37540461`;
var data = d3.csvParse(csv);
var nested = data.map(function(d) {
var obj = {
key: d.type,
values: []
};
for (var prop in d) {
if (prop !== "type") {
obj.values.push({
[prop]: d[prop]
})
}
}
return obj;
});
console.log(nested)
<script src="https://d3js.org/d3.v5.min.js"></script>
Some additional comments:
What yo have in your question is not a JSON, that's just a simple JavaScript object.
What you call an array at the end of your question is neither an array nor an object, that's actually invalid.
Finally, don't use numbers for your property names.

Sorting json objects by specific value

I am sending data that I have already sorted by number of counts, from my controller in Laravel to my script file. Json data that I am sending looks like this:
{"5":{"title":"Coop post title","summary":"dbsbsb","count":5},
"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},
"6":{"title":"Coop's post","summary":"sdbadbb","count":3},
"0":{"title":"sdvsdv","summary":"dsvsdv","count":2},
"4":{"title":"sdvsdv","summary":"dsvsdv","count":1}}
But when I parse json data like this in my script file data gets random again:
var cleanData = $.parseJSON(data);
console.log(cleanData);
And then I get in console data that looks like this:
Object {0: Object, 4: Object, 5: Object, 6: Object, 7: Object}
0:Object
count:2
summary:"dsvsdv"
title:"sdvsdv"
__proto__:Object
4:Object
count:1
summary: "dsvsdv"
title: "sdvsdv"
__proto__:Object
5:Object
count:5
summary: "dbsbsb"
title: "Coop post title"
__proto__: Object
6:Object
count:3
summary: "sdbadbb"
title: "Coop's post"
__proto__: Object
7:Object
count:5
summary: "fdsbdfsbsffd"
title: "Example article"
__proto__: Object
You can sort using lodash#sortBy:
_.sortBy(collection, [iteratees=[_.identity]])
Creates an array of elements, sorted in ascending order by the results of running each element in a collection (Array|Object) thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).
var cleanData = {"5":{"title":"Coop post title","summary":"dbsbsb","count":5},"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},"6":{"title":"Coop's post","summary":"sdbadbb","count":3}, "0":{"title":"sdvsdv","summary":"dsvsdv","count":2}, "4":{"title":"sdvsdv","summary":"dsvsdv","count":1}};
cleanData = _.sortBy(cleanData, ['count']);
console.log(cleanData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

Javascript object is in array but can't access it

I have a for loop which iterates through currentObject in response.
This code:
console.log(response[currentObject]);
Clearly shows that response[currentObject] has among other properties, "start".
However, this code tells me the variable is undefined:
console.log(response[currentObject].start);
Why is this? Note that "start" is a date variable.
Here is the whole function:
function(response) {
for (var currentObject in response) {
//Parsing the data before its used
//"17\/10\/2012 20:55:00"
var phpStartDate = response[currentObject].start;
console.log(response[currentObject]);
var phpStopDate = response[currentObject].stop;
var datePartsStart = phpStartDate.match(/(\d+)/g);
var datePartsStop = phpStopDate.match(/(\d+)/g);
var parsedDateStart = new Date(datePartsStart[2], datePartsStart[1], datePartsStart[0], datePartsStart[3], datePartsStart[4], datePartsStart[5]);
var parsedDateStop = new Date(datePartsStop[2], datePartsStop[1], datePartsStop[0], datePartsStop[3], datePartsStop[4], datePartsStop[5]);
response[currentObject].start = parsedDateStart;
response[currentObject].stop = parsedDateStop;
//debugger;
};
return response;
}
Forgot to add, I'm using jQuery 1.8.2, which I believe handles dates differently than 1.7 (but I can't use 1.7 because I had a whole bunch of other problems with it!)
Here is the output of console.log(response):Object
data: Array[3]
0: Object
hourly: "4.00"
id: "40"
staff: "James Hadley"
start: "2012-09-25 00:00:00"
stop: "2012-09-27 00:00:00"
__proto__: Object
1: Object
hourly: "25.00"
id: "39"
staff: "James Hadley"
start: "2012-10-17 21:12:00"
stop: "2012-10-26 02:30:00"
__proto__: Object
2: Object
length: 3
__proto__: Array[0]
total: 3
__proto__: Object
I guess it's a timing issue, because the console.log object is live. Try
console.log(JSON.stringify(response[currentObject]));
I bet it does NOT include start even thought without stringify it does. Your response is asynchronous and you access start too early (your code doesn't show that part).
Now with your comment it's obvious. It's an array and you are missing and index, e.g. 0.
console.log(response[currentObject][0].start);
use
currentObject.start = parsedDateStart
instead of
response[currentObject].start = parsedDateStart

difference between 2 objects/arrays

i have 2 objects, which are associated arrays from PHP in JSON. They have an structure like that´:
[object]
["green"]
['value1']=integer
['value1']=array...
["blue"]
['value1']=integer
['value1']=array...
[...]
The 1st Version of this object is loaded from webserver periodically using JSON.
By receiving this new JSON string from webserver, the current object moved to the variable "oldObj" while the new data stored into the variable "newObj".
It could be possible, that the new object will have less elements than the old object, like this:
[newObj]
["green"]
['value1']=integer
['value1']=array...
As you can see: "blue" is missing.
Now i need this elements which are part of the old Object / that means: which are missing at the new object (at this example: element "blue")
I tried the following, but without any success:
[...]
var newObj=data;
$.each (oldObj,function(i,n)
{if (newObj.i.length<1) {alert('missing: '+i);}
}
);//end foreach
Error message: "newObj.i is undefined"
According to your description, I think newObj or oldObj can be wrote as:
var newObj = {
"green": [
integer,
[array]
],
"blue": [
integer,
[array]
]
};
Is it right?
You could use :
for(p in Obj){
if(Obj.hasOwnProperty(p)){
// do something with p
}
}
to loop through the Obj's properties.

Categories

Resources