Вопрос

I want to extend an object in a specific position in an array, without having to send the whole array again.

Example:

You start out with the array like this:

sensors = [{value: 10}, {value: 20}];

Now say I want to change the value of the second sensor, I can do this in jQuery:

newSensorValue = {1: {value:30}};
$.extend(true, sensors, newSensorValue);
// sensors = [{value: 10}, {value: 30}];

However, if the array is not directly the object that is merged, this does not work:

node = {x: 10, y: 10, node_id: 1, sensors: [
    {sensor_id: 1, value: 10}, 
    {sensor_id: 2, value: 20}
]};
newNodeData = {sensors: {
    1: {value:30}
}};
$.extend(true, node, newNodeData);
// node = {x: 10, y: 10, node_id: 1, sensors: {
//     1: {value:30}
// }};

Why does $.extend() suddenly behave differently if the array is nested in an object?

My own solution would be to create an array of empty objects, only giving the object that I want to change the "value" attribute, like:

newNodeData = {sensors: [
    {}, {value: 30}
]};

Since this seems rather ugly, is there a better way to do this? I would prefer to keep the sensors attribute an array, since I like to use forEach to go through each sensor quickly.

EDIT: forgot to mention that if I do

$.extend(true, node.sensors, newNodeData.sensors);

It works the same as in the first example (i.e. it works)

Это было полезно?

Решение

You could leave the element empty when you don't want to change it.

node = {x: 10, y: 10, node_id: 1, sensors: [
    {sensor_id: 1, value: 10}, 
    {sensor_id: 2, value: 20}
]};
newNodeData = {sensors: [,{value:30}]};
$.extend(true, node, newNodeData);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top