如何将对象或数组的特定字段级联到现有对象或数组中。(JS和React)

3

我正在尝试从对象中获取特定字段的数据。

  1. 从对象中获取特定字段的数据
  2. 如果可能的话,一次性使用获得的数据设置状态

这里是我想要编辑(使用setState)的taggedItems

taggedItems = {
  0: { id: 0, width: 40, height: 40, image: null, base64: null },
  1: { id: 1, width: 200, height: 200, image: null, base64: null },
  2: { id: 2, width: 80, height: 80, image: null, base64: null }
}

我正在从图像中裁剪 taggedItems。我得到了imagebase64数据。

for (var key in taggedItems) {
    ..
    // Get successURI, base64 value
    // Store it to array or object (Can store them in array, object or any type. 
    // Because I don't prefer to setState in the for-loop.
    // exampleArray = [
    //   { id: 0, image: 'file:path1', base64: 'ksdnflksdf' },
    //   { id: 1, image: 'file:path2', base64: 'fldmlkflkj' },
    //   { id:2, image: 'file:path3', base64: 'glkmdlfg' },
    // ]

// HERE IS THE PROBLEM: I want to setState all of items at once(if it's possible) 
setState({taggedItems: ???}); 

在上面调用setState之后,this.state.taggedItems的预期输出将为:
taggedItems = {
   0: { id: 0, width: 40, height: 40, image: 'file:path1', base64: 'ksdnflksdf' },
   1: { id: 1, width: 200, height: 200, image: 'file:path2', base64: 'fldmlkflkj' },
   2: { id: 2, width: 80, height: 80, image: 'file:path3', base64: 'glkmdlfg' }
}

无论如何我都会将对象转换为数组,以便将数据发送到JSON中,所以请随意使用任何类型的变量(数组或对象)。


各位大佬!请随意帮我编辑并改进我的问题 :) 我非常感激。 - merry-go-round
1个回答

4

不确定我是否理解正确,但听起来你只是想合并两个数组中的对象。如果是这种情况,您可以使用.map和扩展运算符轻松实现:

const taggedItems = [
  {id:0, width:40, height:40, image:null, base64:null},
  {id:1, width:200, height:200, image:null, base64:null},
  {id:2, width:80, height:80, image:null, base64:null}
];

const exampleArray = [
  {id:0, image: 'file:path1', base64: 'ksdnflksdf'},
  {id:1, image: 'file:path2', base64: 'fldmlkflkj'},
  {id:2, image: 'file:path3', base64: 'glkmdlfg'},
];

const merged = taggedItems.map((tagged, i) => {
  return {
    ...tagged,
    ...exampleArray[i]
  };
});

console.log(merged);

更多信息

有关对象扩展的更多信息以及一些可能有助于解释的评论:

const merged = taggedItems.map((tagged, i) => {
  // for every item in `taggedItems` return a new object
  return {
    // take all properties from `tagged`
    ...tagged,
    // get all properties from `exampleArray[i]`
    ...exampleArray[i]
  };
  // The new object will contain all properties from `tagged` + `exampleArray[i]` in that order.
  // If there are duplicated the latter one will overwrite.
});

这正是我正在寻找的。 - merry-go-round
能否解释一下它是如何工作的?它就像魔法一样。谢谢。 - merry-go-round
1
@JohnBaek 很高兴我能帮到你!我添加了一些注释,希望能让它更清晰明了。 - Austin Greco
1
@AustinGreco 这太棒了,我学到了新东西,只是要补充一点,return内部的顺序很重要(你已经提到了),否则后面的属性将覆盖前面的属性。 - brk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接