Asif kaif
Asif kaif

Reputation: 45

Merge two arrays into one Array of objects React

I want merge two separate arrays into one array of objects

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},]

on buttonClick

<button onClick={mergeArray}>Merge Array</button>

Upvotes: 1

Views: 4468

Answers (6)

jsejcksn
jsejcksn

Reputation: 33691

You can use a function to combine multiple arrays, assigning each value to a key at its index. This will work not just for those two arrays, or only two arrays, but any number of 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/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/[email protected]/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>

Upvotes: 0

Yves Kipondo
Yves Kipondo

Reputation: 5603

As for each fruit in the fruits state there is a price in the price state. You can loop over each fruit and create an object with fruit and price key like bellow using the Array.prototype.reduce

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);

Upvotes: 0

SARAN SURYA
SARAN SURYA

Reputation: 554

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. Also using maps in setState works easier with state change in react. The map will yield a array as a result and you can directly use them with the state change.

Upvotes: 3

Muhammad Awais
Muhammad Awais

Reputation: 97

you can use javascript concat function for this, update your funtion with this

  const mergeArray= ()=>{
      const mergeArray= price.concat(fruits);
     setSampleArray(mergeArray) 
}

Upvotes: 0

sedhal
sedhal

Reputation: 520

You can do this using the map function to merge 2 array columns in a single array of objects.

let array = [];
fruits.map((fruit, i) => {
  let json = {
    [fruit]: price[i]
  }
  array.push(json);
})
setSampleArray(array);

Upvotes: 0

sptm
sptm

Reputation: 319

You can do it like this:

const mergeArray = [];
for (i = 0; i < fruits.length; i++) {
  mergeArray[i] = { fruit: fruits[i], price: prices[i] };
}

Upvotes: 2

Related Questions