Creating a new array from an existing array using .Map

63 views Asked by At

I have this code:

const newArray = sheet.map((obj) => {
    const { Name, reppertota, dempertota } = obj;
    return { Name, reppertota, dempertota };
  });

"sheet" is the name of my existing array and "Name", "reppertota" and "dempertota" are the elements within my objects (in the sheet array) that I want to use to create a new array. Basically, I want my 'newArray' to have objects containing the "Name, reppertota and dempertota" elements from the existing array. However, whenever I run this code I get an "unexpected token" error on the first "const" in the first line. I am not sure where I am making the mistake, does anyone have insight? I am doing this in ObservableHQ by the way.

I tried doing this:

DataTwo = {
      const newArray = sheet.map((obj) => {
        const { Name, reppertota, dempertota } = obj;
        return { Name, reppertota, dempertota };
      });
    }

I thought that maybe I had to assign all of this to a variable but I got an "undefined" error but the "unexpected token" error was gone. Any help anyone?

1

There are 1 answers

0
vsjonas On

Obervable is not entirely vanilla javascript. As is says in the docs:

A cell body can be a simple expression, such as a number or string literal, or a function call.

So either you just leave the const:

newArray = sheet.map((obj) => {
const { Name, reppertota, dempertota } = obj;
return { Name, reppertota, dempertota };
});

Or you treat is like a function:

{
const newArray = sheet.map((obj) => {
    const { Name, reppertota, dempertota } = obj;
    return { Name, reppertota, dempertota };
  });
  return newArray
}

For further differences see the docu: oberservable docu