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

时间:2017-12-04 05:12:45

标签: javascript reactjs lodash

我正试图......

  1. 从对象
  2. 中获取特定的数据字段
  3. 立即使用获取的数据设置状态(如果可能)
  4. 这是我要编辑的taggedItems(setState)。

    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: ???}); 
    

    上面this.state.taggedItems之后setState的预期输出

    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中,因此请随意使用任何类型的变量(数组或对象)。

1 个答案:

答案 0 :(得分: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);




更多信息

More info about object spread以及一些可能有助于解释的评论:

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.
});