我正试图......
这是我要编辑的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
。我收到了image
和base64
个数据。
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中,因此请随意使用任何类型的变量(数组或对象)。
答案 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.
});