gpt4 book ai didi

javascript - 在 react js中更新对象数组中的值

转载 作者:行者123 更新时间:2023-12-04 13:13:40 25 4
gpt4 key购买 nike

我正在尝试合并从 2 个不同的 api 调用中获得的两个对象(此处的示例只是一个示例)。如何在用户状态下将对象的 UserId 数组和 userCredentials 数组合并在一起?我希望状态看起来像这个用户:[{id: 1, name"john", country="de"},{id: 2, name"micheal", country="us"}]

...
import React from "react";
import "./styles.css";

export default class App extends React.Component {
constructor() {
super();
this.state = {
user: []
};
}
componentDidMount() {
//api call 1 receiving user Id and name
const UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
this.setState({ user: UserId });

//api call 2 receiving userCredentials
const userCredentials = [
{ id: 1, country: "de" },
{ id: 1, country: "us" }
];

this.setState({
user: { ...this.state.user, credentials: userCredentials }
});
}

render() {
console.log("values", this.state);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
</div>
);
}
}


...

我的示例代码是

https://codesandbox.io/s/fancy-water-5lzs1?file=/src/App.js:0-754

最佳答案

基本上您需要通过 1 个数组进行映射,并查找数组中的每个对象是否存在于另一个数组中,然后使用扩展运算符并在映射回调中返回合并的对象

Working demo

使用下面的代码:

    // option 1 - if you know the keys of the object
let merged = UserId.map(u => {
const user = userCredentials.find(uc => uc.id === u.id);
if (user) u["country"] = user.country;
return u;
});

// option 2 - generic merge
let merged2 = UserId.map(u => {
const user = userCredentials.find(uc => uc.id === u.id);
if (user) return { ...u, ...user };
return u;
});

关于javascript - 在 react js中更新对象数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62273705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com