3
 data: [],

 ... 

I load data from API call into data array. Then I try to arrange the data array into a map which can consist of a key, value pairs (value can be itself array) using below.

    const dataMap = {};
    for (let i = 0; i < data.length; i+=1) {
      const key = data[i].product.name;
      const value = data[i];

      if (key in dataMap) {
        dataMap[key].push(value);
      } else {
        dataMap[key] = [value];
      }
    }

But when I do the following I get the following error. What I am doing wrong?

{[...dataMap].map(([key, value]) => {}

Invalid attempt to spread non-iterable instance

This is my dataMap enter image description here

DataMap is correctly calculate but when i iterate using the following code

Object.entries(dataMap).map((key, value) => {
          console.log(key);
          console.log(value)
 })

it prints out the following. Value is some index which i dont understand why ? Value should be an array. My dataMap is a key, value (value is an array)

enter image description here

Saurabh Kumar
  • 14,849
  • 42
  • 118
  • 186

2 Answers2

4

Your problem has nothing to do with react/react-native, its plain javascript:

dataMap is already an object, so you only can spread its entries.

// An empty object assign.
const dataMap = {};

// Shallow copy
const objShallowCopy = {...dataMap};

Also, you can rewrite your for-loops using reduce():

const dataSource = [
  { product: { name: 1 }, value: 10 },
  { product: { name: 1 }, value: 100 },
  { product: { name: 2 }, value: 30 },
  { product: { name: 2 }, value: 20 }
];

const dataMap = dataSource.reduce((acc, curr) => {
  const prodArr = acc[curr.product.name];
  return { ...acc, [curr.product.name]: prodArr ? [...prodArr, curr] : [curr] };
}, {});

console.log(dataMap);

Moreover, Object.entries returns an entries array so you need to fix your loggings:

// Bug
Object.entries(dataMap).map((key, value) => {
  console.log(key);
  console.log(value);
});


// Good
Object.entries(dataMap).map((([key, value]), index) => {
  console.log("key", key);
  console.log("value", value);
  console.log("index", index);
});
piet.t
  • 11,035
  • 20
  • 40
  • 49
Dennis Vash
  • 31,365
  • 5
  • 46
  • 76
0

dataMap is object, not an array. You cannot do [...dataMap].

You can convert dataMap to arrays of keys with Object.keys(dataMap) or to array of values with Object.values(dataMap)

So erroneous line should look like

Object.keys(dataMap).map(key => /* dataMap[key] will be value */)
Fyodor
  • 7,344
  • 1
  • 20
  • 30