【问题标题】:React Array spread some common data for all objectsReact Array 为所有对象传播一些公共数据
【发布时间】:2021-07-20 15:28:51
【问题描述】:

我正在学习 React,遇到了一个对我的关卡来说有点棘手的问题。从我的 API 调用中,我得到一个对象数组的响应。我想提交数据添加一些对象数据。为了了解响应的外观,这是一个示例(它是 JSON 数组)一些数据想要在数组对象数据 {school:"test",schoolId:"2"}

中传播
Response

data = [
  {0: {name: "tom"}},
  {1: {name: "Pope"}},
  {2: {name: "jack"}}
 ];


Response to want send like
data = [
   {
name: "tom",
school :"testing",
schoolId:"2"
},
   {
name: "Pope",
school :"testing",
schoolId:"2"},
   {
name: "jack",
school :"testing",
schoolId:"2"}
 ];

【问题讨论】:

  • 只需在您的数据上使用.mapdata.map(item => ({...wrapper, item})) where wrapper = { school: 'testing'. schoolOd: 2}

标签: javascript arrays json reactjs


【解决方案1】:

在您的原始数组上使用.map..

定义你想要合并的对象(例如:包装器),然后在.map中简单地展开它

const data = [
  {name: "tom"},
  {name: "Pope"},
  {name: "jack"}
];

const wrapper = {
  school: 'testing',
  schoolId: 2
};

const result = data.map(item => ({...wrapper, ...item}));

console.log(result);

/*
[
  { school: 'testing', schoolId: 2, name: 'tom' },
  { school: 'testing', schoolId: 2, name: 'Pope' },
  { school: 'testing', schoolId: 2, name: 'jack' }
]
*/

Live version

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多