简体   繁体   English

Javascript Map函数不保留原始对象

[英]Javascript Map function does not preserve the original object

I have a scenario wherein i have 我有一种情况

var data = [
    {
        "x": 1,
        "y": 0.27,
        "classifier": 1
    },
    {
        "x": 2,
        "y": 0.88,
        "classifier": 1
    }
]

I want another object data2 with y=1-y, which i obtain with: 我想要另一个具有y = 1-y的对象data2,它是通过以下方式获得的:

var data2 = data.map(function(el) {el.y = 1-el.y; return el});

data2[0]
Object {x: 1, y: 0.73, classifier: 1}

data2[1]
Object {x: 2, y: 0.12, classifier: 1}

which is the correct form that i want the data in. However the issue is i want to preserve the original data as well. 这是我想要数据的正确形式。但是问题是我也想保留原始数据。 Right now even data has mutated data. 现在,即使数据也已突变。

data[0]
Object {x: 1, y: 0.73, classifier: 1}

data[1]
Object {x: 2, y: 0.12, classifier: 1}

Is map the right function to use here? 地图在这里使用正确的功能吗? Am i using it correctly? 我使用正确吗?

You're modifying the original element object, which isn't a full deep copy of the original data. 您正在修改原始元素对象,它不是原始数据的完整深层副本。

Create a copy of el in the function and then calculate the new .y . 在函数中创建el的副本,然后计算新的.y For example: 例如:

var data2 = data.map(function(el) {
  return {
    x : el.x,
    y : 1-el.y,
    classifier : el.classifier
  };
});

While creating a new array, you let its values point to the original objects, which you mutate by assigning to their object properties. 创建新数组时,可以让其值指向原始对象,您可以通过分配其对象属性来对其进行更改。

Instead you could also create (shallow) copies of the objects with Object.assign : 相反,您还可以使用Object.assign创建(浅)对象的副本:

var data2 = data.map(function(el) { 
    return Object.assign({}, el, { y: 1-el.y });
});

Or with arrow function: 或带有箭头功能:

var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) );

 var data = [ { "x": 1, "y": 0.27, "classifier": 1 }, { "x": 2, "y": 0.88, "classifier": 1 } ] var data2 = data.map( el => Object.assign({}, el, { y: 1-el.y }) ); console.log (data); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM