0

I have a function which return a nested Array in this format, the length varies

const funcOutput = [

    ["marc doo",9.55],
    
    ["jack doo",10.55],
    
    ["flack doo",12.55],
    
    ["back doo",14.55],
   
   ]

In need to transform the array into a table suitable format


const tableInsert = [
    {position: 1, fullName: "marc doo", result: 9.55},

    {position: 2, fullName: "jack doo", result: 10.55},

    {position: 3, fullName: "flack doo", result: 12.55},
    {position: 4, fullName: "back doo", result: 14.55},
   
   ];






I tried to use varies inner and outer counters to loop over the nested Arrays
and create a new Object which does not return the desired result



  const container = [];



  let outerCounter = 0;

  for (let arrays of funcOutput) {
    outerCounter++;
    let innerCounter = 0;

    const myObjects = { fullName: "--", result: 0 };

    const deepCopy = { ...myObjects };

    for (let prop in Object.keys(deepCopy)) {

     if (innerCounter === 0) {
        Object.assign(deepCopy, {position: (innerCounter +1)});
     }
    
      prop = arrays[innerCounter];

     
      // iterate over object and array at the same time
      // ->

      if (innerCounter === 1) {
        container.push(deepCopy);
      }

      innerCounter++;
    }
    console.log(container);

    return container
  }



1
  • To get position, just remember that the function passed to map takes the element, the index, and the original array as arguments. Commented May 13, 2021 at 19:22

2 Answers 2

1

A nice way to do it would be:

funcOutput.map((list, index) =>  {
    return { position: index + 1, fullName: list[0], result: list[1] };
});
Sign up to request clarification or add additional context in comments.

Comments

1

Using map is a possible option.

The map() method creates a new array populated with the results of calling a provided function where the two arguments are current element in the array and second one is the current index.

const funcOutput = [

    ["marc doo",9.55],
    
    ["jack doo",10.55],
    
    ["flack doo",12.55],
    
    ["back doo",14.55],
   
   ]


const res = funcOutput.map((current, idx) =>  {
    return { position: ++idx, fullName: current[0], result: current[1] };
});

console.log(res)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.