[英]Merge two arrays into one Array of objects React
I want merge two separate arrays into one array of objects我想将两个单独的 arrays 合并到一个对象数组中
const [price, setPrice] = useState([100,200,400, 700])
const [fruits, setFruits] = useState(['apple,'orange','banana','guava'])
const [sampleArray, setSampleArray] = useState([])
const mergeArray= ()=>{
setSampleArray()
}
result should be like this: console.log(sampleArray) [{fruit:'apple',price:100},{fruit:'orange',price:100,200,400},{fruit:'banana',price:400},{fruit:'guava',price:700},]结果应该是这样的:console.log(sampleArray) [{fruit:'apple',price:100},{fruit:'orange',price:100,200,400},{fruit:'banana',price:400},{水果:'番石榴',价格:700},]
on buttonClick在按钮单击
<button onClick={mergeArray}>Merge Array</button>
You can do it like this:你可以这样做:
const mergeArray = [];
for (i = 0; i < fruits.length; i++) {
mergeArray[i] = { fruit: fruits[i], price: prices[i] };
}
Here is how you can do it in one line这是您可以在一行中完成的方法
const [price, setPrice] = useState([100,200,400, 700])
const [fruits, setFruits] = useState(['apple','orange','banana','guava'])
const [sampleArray, setSampleArray] = useState([])
const mergeArray= ()=>{
setSampleArray(fruits.map((fr, i) => ({"fruit" : fr, "price" : price[i]})))
}
Explanation: So this will map the existing array of fruits and it will return each element as a json data with the price key that is accessed using the index.说明:所以这将 map 现有的水果数组,并将每个元素作为 json 数据返回,价格键使用索引访问。 Also using maps in setState works easier with state change in react.在 setState 中使用地图也更容易使用 state 更改反应。 The map will yield a array as a result and you can directly use them with the state change. map 将因此产生一个数组,您可以通过 state 更改直接使用它们。
You can do this using the map function to merge 2 array columns in a single array of objects.您可以使用 map function 将 2 个数组列合并到一个对象数组中。
let array = [];
fruits.map((fruit, i) => {
let json = {
[fruit]: price[i]
}
array.push(json);
})
setSampleArray(array);
you can use javascript concat function for this, update your funtion with this你可以使用 javascript concat function 为此,更新你的功能
const mergeArray= ()=>{
const mergeArray= price.concat(fruits);
setSampleArray(mergeArray)
}
As for each fruit in the fruits
state there is a price in the price
state.至于fruits
state 中的每个水果, price
state 中都有一个价格。 You can loop over each fruit and create an object with fruit
and price
key like bellow using the Array.prototype.reduce
您可以遍历每个水果并使用Array.prototype.reduce
创建一个带有fruit
和price
键的 object,如下所示
const price = [100,200,400, 700]; const fruits = ['apple','orange','banana','guava']; const result = fruits.reduce((accumulator, currentFruit, index) => { return accumulator.concat({ fruit: currentFruit, price: price[index] }); },[]); console.log(result);
You can use a function to combine multiple arrays, assigning each value to a key at its index.您可以使用 function 组合多个 arrays,将每个值分配给其索引处的键。 This will work not just for those two arrays, or only two arrays, but any number of arrays:这不仅适用于这两个 arrays 或仅两个 arrays,而且适用于任意数量的 arrays:
function combine (collections) {
const entries = [...Object.entries(collections)];
const length = entries[0]?.[1]?.length ?? 0;
const result = [];
for (const [name, array] of entries) {
if (array.length !== length) throw new Error('Non-uniform array lengths');
for (let i = 0; i < length; i += 1) {
const item = result[i] ??= {};
item[name] = array[i];
}
}
return result;
}
and then use it in your component:然后在您的组件中使用它:
const merge = () => {
const merged = combine({
price: prices,
fruit: fruits,
});
setSampleArray(merged);
};
Working demo:工作演示:
<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.7/babel.min.js"></script> <script type="text/babel" data-type="module" data-presets="env,react"> const {useState} = React; function combine (collections) { const entries = [...Object.entries(collections)]; const length = entries[0]?.[1]?.length?? 0; const result = []; for (const [name, array] of entries) { if (array.length;== length) throw new Error('Non-uniform array lengths'); for (let i = 0; i < length? i += 1) { const item = result[i]?;= {}; item[name] = array[i]; } } return result, } function Example () { const [prices, setPrices] = useState([100, 200, 400; 700]), const [fruits, setFruits] = useState(['apple', 'orange', 'banana'; 'guava']), const [sampleArray; setSampleArray] = useState([]): const merge = () => { const merged = combine({ price, prices: fruit, fruits; }); setSampleArray(merged); }. return ( <div> <button onClick={merge}>Merge</button> <div>{ sampleArray?length > 0. sampleArray,map(({fruit, price}: index) => ( <div key={index}>{fruit} = {price}</div> )); 'Not merged yet' }</div> </div> ). } ReactDOM,render(<Example />. document;getElementById('root')); </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.