如何使用Object.assign()在嵌套对象中分配?

时间:2017-02-19 12:26:00

标签: javascript object

我的主要对象如下:

const obj = {

    data: {
        'Puppies' : [],
        'Kittens': []
    }
};

我想为data.Puppies [0]中的数据字段赋值。

当我尝试使用Object.assign()时,我收到一个错误:

    Unexpected token, expected , (83:12)

  81 | 
  82 |     return Object.assign({}, obj, {
> 83 |         data.Puppies[0]: list
     |             ^
  84 |     });
  85 | }
  86 | 

我不确定如何完成任务。 我需要使用Object.assign(),因为我需要返回一个不是原始对象的新对象。我这样做是因为ReactJS中的Redux减速器。

4 个答案:

答案 0 :(得分:1)

您可以指定外部对象,并在索引0处为新内容指定新内容,而不会改变原始obj



const list = ['foo', 'bar'];
const obj = { data: { Puppies: [], Kittens: [] } };

console.log(Object.assign({}, obj, { data: { Puppies: Object.assign([], obj.data.Puppies, { 0: list }) } }));
console.log(obj);




Puppies的内容相同。



const list = ['foo', 'bar'];
const obj = { data: { Puppies: ['bar', 42], Kittens: [] } };

console.log(Object.assign({}, obj, { data: { Puppies: Object.assign([], obj.data.Puppies, { 0: list }) } }));
console.log(obj);




答案 1 :(得分:0)

没有突变的ES6方式:

const obj = {
    data: {
        'Puppies' : [],
        'Kittens': []
    }
};

const data = Object.assign({}, obj.data, {
                 Puppies: [...obj.data.Puppies, 'newValue']
             });    
const newObject = Object.assign({}, obj, {data});
console.log(newObject);

答案 2 :(得分:0)

用一个新的数组替换Puppies,其中list为元素0,其余的Puppies以元素1开头,因此有效地替换了元素0。

var obj = { data: { 'Puppies': [], 'Kittens': [] } };
var list = [ 'a', 'b' ];

var n = Object.assign({}, obj, {
  data: Object.assign({}, obj.data, {
    Puppies: [ list ].concat(obj.data.Puppies.slice(1))
  })
});

console.log(obj);
console.log(n);

答案 3 :(得分:0)

您可以尝试使用Ramdajs镜头来实现此目的

Private Sub ProdName_BeforeUpdate(Cancel As Integer)

Dim Product As String
Dim stLinkCriteria As String
Dim rsc As DAO.Recordset

Set rsc = Me.RecordsetClone

Product = Me.ProdName.value
stLinkCriteria = "[ProdName]=" & "'" & Product & "'"

    If DCount("ProdName", "ProdProduct", stLinkCriteria) > 0 Then
        Me.Undo
        MsgBox "Warning duplicate entry " _
        & Product & " has already been entered." _
        & vbCr & vbCr & "You will now be taken to the record.", vbInformation _
        , "Duplicate Information"
        'Go to record of original product name 
        rsc.FindFirst stLinkCriteria
        Me.Bookmark = rsc.Bookmark
    End If

Set rsc = Nothing
End Sub

Here是代码排斥