Home > Enterprise >  Combine Array and String in Mapping in React
Combine Array and String in Mapping in React

Time:01-08

I need to combine rows and rows2. If either of them don't have a value, their values is "none". How do I combine them? The problem now is that its creating multiple rows that is empty.

Codesandbox Edit combine-array-and-string-in-mapping-in-react

CodePudding user response:

You can use the syntax for result below. Just replace the map callback function with whatever you want:

const rows = [
  {
    name: "frozen yogurt",
    calories: 22,
    fat: 33,
    carbs: 44,
    protein: 44
  },
  // ...
];

const rows2 = "none";

const result = [...(Array.isArray(rows) ? rows : []), ...(Array.isArray(rows2) ? rows2 : [])]
  .map(row => /* whatever you want here, but I'll use */ row);

console.log(result);

Or you can make a function and re-use it:

function arrayValueOrEmptyArray (value) {
  return Array.isArray(value) ? value : [];
}

const rows = [
  {
    name: "frozen yogurt",
    calories: 22,
    fat: 33,
    carbs: 44,
    protein: 44
  },
  // ...
];

const rows2 = "none";

const result = [...arrayValueOrEmptyArray(rows), ...arrayValueOrEmptyArray(rows2)].map(row => row);

console.log(result);

  •  Tags:  
  • Related