开发者

Is associative array element the same as an object field?

开发者 https://www.devze.com 2023-02-07 02:20 出处:网络
I have an object that looks something like this. var obj = { speed: 10, volume: 14, aux_deform: 1.8, energy: 21.5,

I have an object that looks something like this.

var obj = {
    speed: 10,
    volume: 14,
    aux_deform: 1.8,
    energy: 21.5,
    aux_energy: 0.2
}

There will be additional fields/properties added at runtime, so the object can contain any number of properties at any given time. As you can see in my object example, some properties can start with "aux_".

Now, I want to create another object from this one that contains only properties that start with "aux_".

T开发者_JAVA技巧he way I am doing it now is something like this.

var newObj = [];
for(prop in obj)
{
    if (prop.startsWith('aux_'))
    {
        newObj[prop] = obj[prop];
    }
}

Now I have a new object and I can do something like:

alert(newObj.aux_energy);

This works ok, but I am wondering if this is the right approach. Is there any easier way, or a more elegant way for what I am trying to achieve? Are there any (security or technical) issues/problems with this way of creating objects?

And the question from the title: is the newly created object actually an associative array with properties as keys (since it's created that way) or is there any difference.


There are no associative arrays in Java Script, there are only JSON objects which can be used in place of associative arrays. What you did here is that you have declared an array called newObj and then added properties to this array. It could lead to unexpected behaviors when trying to use buit in Array methods or when iterating over it. The main difference between JSON objects and arrays is that properties in objects aren't sortable and iterating over them can produce random and unpredictable output.

More appropriate way to write that would be to declare an object newObj = {} and then just copy the properties you need.

One thing to note - if you will have arrays or objects as values for properties you will copy references to these objects. If you'd like to be able to edit these values independently from the original object you'd have to deep copy these values - check this question for how to on that What is the most efficient way to deep clone an object in JavaScript?

Apart from that it's the only way to do that and it's perfectly fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消