locked
I have a question regarding the proper javascript for mapping out an array: How can I change key names in an object array in javascript based on the column name having a matching record in a 2nd array. RRS feed

  • Question

  • I have an object array with data coming in from an excel spreadsheet. The dataArray can come in with whatever columns wanted. I also have an object array as such: const expectedColumns= [
      { id: 0, text: "Name", mapColumn: "Person" },
        { id: 1, text: "Address", mapColumn: "Add" },
        { id: 3, text: "State", mapColumn: "State" },
        { id: 5, text: "Phone", mapColumn: "Number" },
      ];

    The mapColumn in the expectedColumns array gets filled in based on the dataArray. Basically I expect to have 6 columns "Name, Address, City, State, Zip, Phone", and the way I know the columns that will be matched in the dataArray I would look at the mapColumn and see what the column name is called in the dataArray and pull out those corresponding columns from the dataArray into a new array with the old column name from the dataArray using the text column from the expectedColumns array as the new key of the objects in the array coming from the dataArray.

    I tried doing
        const NewArrayFromDataArray = data.map((e) =>({ "Phone1": e["Phone"], "Age1": e.Age}));
    That works to change the key name, but I don't know when I map it out what columns from the array I want to take out. I want it to be based on the expectedColumns array. 

    The length of columns in the dataArray doesn't have to be the same amount as the rows in the ExpectedColumns mapColumn


    if the expectedColumns array would look like this

    How would I go about doing this?

    in the dataArray there might be 
    const data = [
      { id: 0, Type : "insert", Person: "Sarah", Number: "666-777-9999", Add: "123 South Street", State:"NY"},
       { id: 0, Type : "update", Person: "Hether", Number: "123-456-9699", Add: "4 North Street", State:"OH" },
        { id: 0, Type : "delete", Person: "John", Number: "444-444-4444", Add: "56 West Street", State: "MA" },
      ];

    I want to extract just the specific columns from the dataArray that match a mapColumn in the expectedColumns array and rename it to the corresponding text in the expectedColumns array.

    Debra has a question

    Friday, December 4, 2020 5:36 PM

Answers