[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.javascript

Push object to array syntax

antony

7/25/2014 10:04:00 PM

I'm struggling with the syntax when trying to create an array of objects.


I have a JSON feed which has a boat load of data in a don't need so I'm just grabbing the relevant values and creating a new array (it's to be using in a leaflet.js map btw)


The format I need is:

markers: {
marker-name-1:{"lat":32.0852999,"lng":34.7817676},
marker-name-2:{"lat":30.0444196,"lng":31.2357116}
}


Using:

var newArray = [];

feed = Datafeed.query(function (response){

_.each(response, function(rows) {

var latstr = rows.custom_fields._wp_geo_latitude;
var lngstr = rows.custom_fields._wp_geo_longitude;
var title = rows.title;

var result = {};
result [title] = {lat : latstr , lng : lngstr};
newArray.push(result);

});
});


I get:

{"marker-name-1":{"lat":"32.0852999","lng":"34.7817676"}},
{"marker-name-2":{"lat":"30.0444196","lng":"31.2357116"}}

They are all separate objects which won't work dammit!

Some help on how I can construct what I'm after would be much appreciated.

Thanks

Antony
8 Answers

ram

7/25/2014 10:21:00 PM

0

antony@maxwelllucas.com writes:
>newArray.push(result);
>{"marker-name-1":{"lat":"32.0852999","lng":"34.7817676"}},
>{"marker-name-2":{"lat":"30.0444196","lng":"31.2357116"}}

Wild guess: something like:

for( var name in result )if( result.hasOwnProperty( name ))
{ newArray[ name ]= result[ name ]; break; }

?

Thomas 'PointedEars' Lahn

7/26/2014 9:08:00 AM

0

Stefan Ram wrote:

> antony@maxwelllucas.com writes:
>> newArray.push(result);
>> {"marker-name-1":{"lat":"32.0852999","lng":"34.7817676"}},
>> {"marker-name-2":{"lat":"30.0444196","lng":"31.2357116"}}
>
> Wild guess: something like:
>
> for( var name in result )if( result.hasOwnProperty( name ))
> { newArray[ name ]= result[ name ]; break; }
>
> ?

GIGO. This code will add the first own enumerable property of the object
referred to by â??resultâ? to the object referred to by â??newArrayâ?, or
overwrite an existing one, and then exit. But the former object was created
by the OPâ??s code just two line before that, and one line before the only
relevant property has been added; so the property name is *known* and the
error-prone, though not completely cluless, iteration-assignment is
unnecessary.

This problem is, in essence, so simple that it does not excuse wild guesses.
Please test before you post. Nobody is helped by posting half-knowledge.

JavaScript/ECMAScript is not like PHP, for example. There are no built-in
associative arrays. Using the bracket property accessor syntax LHS does not
add an array element per se (only for particular numeric property names).
Using Array instances (as created with the Array initialiser, â??[]â?) when you
do not need Array properties â?? *numeric* indexes aso. â?? is wrong.

The following could be the solution the OP is looking for:

/* we only need an Object instance here */
var o = {
/* create _data_ object (ES 5+) */
markers: Object.create(null)
};

var feed = Datafeed.query(function (response) {
// â?¦

_.each(response, function (rows) {
// â?¦

var markers = o.markers;

/*
* sanitize title here so that the object is not borked by a marker
*/

/*
* ES 3+; use markers[title] _here_ for more backwards compatibility
*/
if (title in markers)
{
/*
* or you could make the property value a reference to
* an Array instance here, accumulating data for same-named markers
*/
console.warn('Ignored duplicate marker: "' + title + '"');
}
else
{
markers[title] = {lat: latstr, lng: lngstr};
}
});
});

The Object instance having a put() method that does the sanitizing and
checks would even be cleaner. jsx.map.Map() could be extended, or a Map
Proxy (ES 6) could be used directly.

Unfortunately, the OP has not read the FAQ on how to ask questions the smart
way, so one cannot be sure as to the solution. Also, them using the borken
Google Groups instead of a proper newsreader, it is not likely that many
knowledgable people will read their posting.

--
PointedEars
FAQ: <http://PointedEars.... | SVN: <http://PointedEars.de...
Twitter: @PointedEars2 | ES Matrix: <http://PointedEars.de/es-...
Please do not Cc: me. / Bitte keine Kopien per E-Mail.

Scott Sauyet

7/27/2014 5:52:00 PM

0

antony@maxwelllucas.com wrote:
> I'm struggling with the syntax when trying to create an array of
> objects.
>
> I have a JSON feed which has a boat load of data in a don't need
> so I'm just grabbing the relevant values and creating a new array
> (it's to be using in a leaflet.js map btw)

It's all right to reduce the data, but you really should show us
the structure of the data you receive. I'm making a guess and
assuming that the callback to Datafeed.query receives an array of
objects, but your sample code (assuming that the `_` is something
like Underscore or LoDash) would work with certain other structures
as well, in which case, my suggestion might not help.

> The format I need is:
> markers: {
> marker-name-1:{"lat":32.0852999,"lng":34.7817676},
> marker-name-2:{"lat":30.0444196,"lng":31.2357116}
> }

I assume you need an object wrapping that up:

{
markers: {
marker-name-1:{"lat":32.0852999,"lng":34.7817676},
marker-name-2:{"lat":30.0444196,"lng":31.2357116}
}
}

If not, I'm not quite sure what you mean.

This code might do what you

var newArray = Datafeed.query(function(response) {
return {markers: response.map(function(rows) {
var obj = {};
obj[rows.title] = {
lat: +rows.custom_fields._wp_geo_latitude,
lng: +rows.custom_fields._wp_geo_longitude
};
return obj;
})};
});

This is making the assumption that `Datafeed.query` returns
to you the result of your callback function. If not, you
would have to structure it slightly differently:

var newArray;
Datafeed.query(function(response) {
newArray = {markers: response.map(function(rows) {
var obj = {};
// ...

And if you need this code to run in environments that don't support
`Array.prototype.map`, you would need either to replace the `map`
call with a library `map` or shim it. A reasonable shim is found
on MDN [1]. A `map` from Underscore or LoDash would be used like

return {markers: _.map(response, function(rows) {
/* ... */
});

The `map` in the Ramda [2] library I've been working on puts the
list after the function, so would work like this:

return {markers: R.map(function(rows) {
/* ... */
}, response);


[1]: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Po...
[2]: <https://github.com/CrossEye...

HTH,

-- Scott

Scott Sauyet

7/28/2014 1:24:00 AM

0

Scott Sauyet wrote:
> [ ... ]
> And if you need this code to run in environments that don't support
> `Array.prototype.map`, you would need either to replace the `map`
> call with a library `map` or shim it. A reasonable shim is found
> on MDN [1]. A `map` from Underscore or LoDash would be used like

Sorry, this incorrect URL was for a different style of code:

> [1]: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Po...

The correct URL is

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ma...

-- Scott

antony

7/28/2014 2:07:00 PM

0

Thanks for the help everyone, some great answers which have taught me a few things and helped me solve the issue.

Thanks again.

lingmaaki

10/29/2014 7:29:00 AM

0

More about JavaScript Array

http://www.corelangs.com/js/basics/a...

Rahul


On Saturday, July 26, 2014 3:34:17 AM UTC+5:30, ant...@maxwelllucas.com wrote:
> I'm struggling with the syntax when trying to create an array of objects.
>
>
> I have a JSON feed which has a boat load of data in a don't need so I'm just grabbing the relevant values and creating a new array (it's to be using in a leaflet.js map btw)
>
>
> The format I need is:
>
> markers: {
> marker-name-1:{"lat":32.0852999,"lng":34.7817676},
> marker-name-2:{"lat":30.0444196,"lng":31.2357116}
> }
>
>
> Using:
>
> var newArray = [];
>
> feed = Datafeed.query(function (response){
>
> _.each(response, function(rows) {
>
> var latstr = rows.custom_fields._wp_geo_latitude;
> var lngstr = rows.custom_fields._wp_geo_longitude;
> var title = rows.title;
>
> var result = {};
> result [title] = {lat : latstr , lng : lngstr};
> newArray.push(result);
>
> });
> });
>
>
> I get:
>
> {"marker-name-1":{"lat":"32.0852999","lng":"34.7817676"}},
> {"marker-name-2":{"lat":"30.0444196","lng":"31.2357116"}}
>
> They are all separate objects which won't work dammit!
>
> Some help on how I can construct what I'm after would be much appreciated.
>
> Thanks
>
> Antony

John Harris

10/29/2014 3:23:00 PM

0

On Wed, 29 Oct 2014 00:29:07 -0700 (PDT), lingmaaki@gmail.com wrote:

>More about JavaScript Array
>
>http://www.corelangs.com/js/basics/a...
<snip>

That web page is wrong about array length.

John

Christoph M. Becker

10/29/2014 4:34:00 PM

0

John Harris wrote:

> On Wed, 29 Oct 2014 00:29:07 -0700 (PDT), lingmaaki@gmail.com wrote:
>
>> More about JavaScript Array
>>
>> http://www.corelangs.com/js/basics/a...
> <snip>
>
> That web page is wrong about array length.

Well, this web page is wrong about several other things as well.

--
Christoph M. Becker