1

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>

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

fruits & price inside map method not must be inside " ".
@ArmanEbrahimi, This is a user preference on how you are wishing to to store your key values, Both works.
2

You can do it like this:

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

Comments

0

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

Comments

0

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

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

Comments

0

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.