On 16-07-2017 06:00, Andrew Poulos wrote:
> The server returns a string which I parse. It becomes an array of
> "simple" objects eg.
> {
> "id":1,
> "colour": "#fff",
> "width": 320,
> "height":240
> }
It seems this app is using some form of "Virtual DOM", or just assigning
styles (Properties / Values) to a given HTML element. In any case, it
would be better using standard CSS property names, e.g "color" instead
of "colour", and strings for width / height values such as "320px" or
"240px". That's because it would be easier to assign styles to an element:
E.g.
var el = document.getElementById("1");
el.style.cssText = "color:#fff;width:320px;height:240px;";
Or:
Object.assign(el.style,
{
"color": "#fff",
"width": "320px",
"height": "240px"
}
);
> To find an object with a specific "id" I use a for loop on the array.
> This is ok but now the arrays I'm getting contain 10s of objects. What
> better way can I use to find a specific object?
As Martin Honnen suggested, you might use the Array's filter() method to
get an array of those objects meeting the filter condition.
However if "id" references a unique element, you'd be ok with the find()
method too. Look up these two Array methods in the MDN:
<
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array>
--
Joao Rodrigues