【问题标题】:Updating the values in an array of objects in react js在反应js中更新对象数组中的值
【发布时间】:2020-09-28 02:31:43
【问题描述】:

我正在尝试合并从 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

【问题讨论】:

  • 您可以使用array.concat(anotherArray) 将两个数组合并在一起。

标签: javascript json reactjs rxjs


【解决方案1】:

您可以使用 'array.concat([])' 将两个数组对象合并在一起。请参见下面的示例。

let UserId = [{ id: 1, name: "john" }, { id: 2, name: "micheal" }];
const userCredentials = [{ id: 1, country: "de" },{ id: 1, country: "us" }];

const newArray = UserId.concat(userCredentials);

由于您已将 UserId 定义为 const,因此您无法更改它。所以你必须让它 let 或 var 来修改变量。

【讨论】:

  • concat 基本上会将所有这些合并在一起,我将拥有一个单独的用户凭据对象。但我想将凭据与 userId 合并。
  • 你能在我尝试的沙盒中做这个改变吗,它返回给我一个包含 4 个数组的状态
  • 你想要这个 [{id: 1, name: "john", country: "de"}] 吗?
  • 如果是这样,您必须使用 array.map 在数组中构造新对象。 gdh 已经回答了这个问题。
【解决方案2】:

基本上你需要通过 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;
    });

【讨论】:

  • 太棒了...如果您愿意,请考虑接受答案..
猜你喜欢
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 2023-01-13
相关资源
最近更新 更多