简体   繁体   English

使用forEach,map或filter克隆和操作嵌套对象,而无需修改原始对象

[英]Cloning and manipulating nested object using forEach, map, or filter without modifying original object

I'm trying to get a handle on using .map, .filter to clone and modify a big nested JSON object based on a deeply nested property. 我正在尝试使用.map,.filter来基于深度嵌套的属性克隆和修改大嵌套的JSON对象。 With the below code, the original data and the filtered data both end up getting modified, but I'm trying to leave the original data intact. 使用下面的代码,原始datafiltered数据都最终会被修改,但是我试图保持原始data不变。 What I'm hoping to do is have the deeply nested concerns array emptied in the final filtered object for a given id, leaving the original data as the original complete data set. 我希望做的是在给定的ID的最终filtered对象中清空深层嵌套的concerns数组,而将原始data保留为原始完整数据集。

var data {...};

var dataFilter = function dataBuild(data) {
  var newData = data;

  newData.service_requests = newData.service_requests.map((request) => {
    request.concerns = request.concerns.filter((concern) => {
      return concern.building_id == 2
    });
    return request;
  });

    return newData;
};

var filtered = dataFilter(data);

Here's a fiddle with what I'm trying to do with the full object in there. 这是我正在尝试使用其中的完整对象的东西。 http://jsbin.com/doyoqinoxo/edit?js,console http://jsbin.com/doyoqinoxo/edit?js,控制台

When you do: 当您这样做时:

var newData = data;

you are simply making a second reference to the same object, so: 您只是在再次引用同一对象,所以:

newData.service_requests = ...

overwrites the value in data.service_requests . 覆盖data.service_requests中的值。

It seems you want newData to be a copy of data , not a reference to the same object. 似乎您希望newData数据的副本,而不是对同一对象的引用。 There are plenty of posts here on how to copy a nested object (a so–called deep copy), eg What is the most efficient way to clone an object? 这里有很多关于如何复制嵌套对象(所谓的深层复制)的文章,例如,克隆对象的最有效方法是什么? , but please ignore the accepted answer unless you are using jQuery. ,但是除非您使用的是jQuery,否则请忽略接受的答案。 Use one of the other answers, like this one . 使用其他答案之一,例如这个

JSIterator .map() creates the new array with the same number of elements or does not change the original array. JSIterator .map()使用相同数量的元素创建新数组,或者不更改原始数组。 There might be the problem with referencing if there is object inside the array as it copies the same reference, so, when you are making any changes on the property of the object it will change the original value of the element which holds the same reference. 如果数组内部复制了相同的引用,则引用可能存在问题,因此,当您对对象的属性进行任何更改时,它将更改具有相同引用的元素的原始值。

The solution would be to copy the object, well, array.Splice() and [...array] (spread Operator) would not help in this case, you can use JavaScript Utility library like Loadash or just use below mention code: 解决的办法是复制对象,好吧,在这种情况下, array.Splice()[...array] (扩展运算符)将无济于事,您可以使用JavaScript工具库(如Loadash)或仅使用下面提到的代码:

const newList = JSON.parse(JSON.stringify(orinalArr))

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

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