close

[Solved] Invalid attempt to spread non-iterable instance on an object

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error Invalid attempt to spread non-iterable instance on an object in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To Solve Invalid attempt to spread non-iterable instance on an object Error ?

  1. How To Solve Invalid attempt to spread non-iterable instance on an object Error?

    To Solve Invalid attempt to spread non-iterable instance on an object Error dataMap is an object, not an array. You cannot do […dataMap]. You can convert dataMap to arrays of keys with Object.keys(dataMap) or to an array of values with Object.values(dataMap) So erroneous line should look like.

  2. Invalid attempt to spread non-iterable instance on an object

    To Solve Invalid attempt to spread non-iterable instance on an object Error dataMap is an object, not an array. You cannot do […dataMap]. You can convert dataMap to arrays of keys with Object.keys(dataMap) or to an array of values with Object.values(dataMap) So erroneous line should look like.

Solution 1

problem has nothing to do with react/react-native, it is 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:

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


// Good Practice
Object.entries(dataMap).map((([key, value]), index) => {
  console.log("key", key);
  console.log("value", value);
  console.log("index", index);
});

Solution 2

dataMap is an object, not an array. You cannot do [...dataMap]. You can convert dataMap to arrays of keys with Object.keys(dataMap) or to an array of values with Object.values(dataMap) So erroneous line should look like.

Object.keys(dataMap).map(key => /* dataMap[key] will be value */)

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment