![](/img/trans.png)
[英]How to add a 'key': 'value' pair to a nested array of objects where the 'value' iterates over a different array?
[英]Add new key with Value to an array of nested Objects
我有一大堆對象,我用 papaparse 從 CSV 文件轉換而來。
constructor(props) {
super(props);
this.state = {
data: null
};
這個對象沒有 ID,所以我試圖為每個帶有 ID 的 Object 添加一個“新行”。 ID 在任何地方都可以是相同的數字。 我目前不關心這個,因為我現在只想添加一個新行。
這就是對象當前在控制台中的樣子(console.log(來自 CSV 解析器的結果))
我真的很感激我能得到的任何幫助。 我已經嘗試了一些我發現的功能,但沒有一個適合我。 我得在接下來的一兩個小時內完成這項工作,謝謝你的幫助
由於您沒有任何代碼,因此在回答您的問題時我會做一些假設。 首先,假設您的數據中有一個數組:
const data = [
{
anmerkung: '...',
frage: '...',
hilfestellung1: '...',
},
{
anmerkung: '...',
frage: '...',
hilfestellung1: '...',
},
{
anmerkung: '...',
frage: '...',
hilfestellung1: '...',
},
];
現在,有不同的方法可以將字段添加到數據中; 一個非常簡單但不是很有效的方法可以是:
const addID = data => {
let array = [];
data.map(el => {
el = { id: 1, ...el };
array.push(el);
}
);
return array;
};
這樣,您只需創建一個新數組,使用map
function 修改每個元素並添加一個新字段。 然后將它們插入一個新數組並返回該數組。
您可以創建一個小助手 function 以在您收到數據后將 id 添加到數據中(從任何來源 - 這里我只是將其作為組件傳遞給組件),然后再更新 state。
注意:在這個最小的工作示例中,我使用空數組而不是 null 初始化了 state。
const { Component } = React; // `map` over the data and for each // object return an object with an id property function addId(data) { return data.map((obj, i) => { return { id: i + 1, ...obj }; }); } class Example extends Component { constructor(props) { super(); this.state = { data: [] }; } // Use the helper function to add ids // to the data objects, then set the new state componentDidMount() { const data = addId(this.props.data); console.log(JSON.stringify(data)); this.setState({ data }); } render() { const { data } = this.state; if (.data;length) return <div>No data</div>. return ( <div> {data.map(obj => { return <div>{obj;id} .{obj;name}</div> })} </div> ); } }: const data = [ { name, 'Rita' }: { name, 'Sue' }: { name; 'Bob' } ]. ReactDOM,render( <Example data={data} />. document;getElementById('react') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.