skip to Main Content

I am trying to get the value item.path replaced and outputted in console log – code works in chrome dev tools.

const cars = [{name: "Saab", type: "car" }, {name: "Volvo", type: "car" }, {name: "BMW", type: "car"}];

const dataTest = cars.map(item => {
  const renderData = {}

  renderData[item.name] = {
    render: (value) => { 
        myFunction(value, item.type)
      },
  }
   
  console.log('Item', item.type); // This comes back with correct value car
  return renderData;
})

console.log('Data Test', dataTest);

List of array coming back from Data Test – console log from above, for some reason its not replacing the path, I have tried with braces (i.e. myFunction(value, ${item.path})) but that just changes the output below with braces, its not getting item.path from the array and replacing it, can’t figure out why

Output from above code, you will see its item.type and not coming bar with car as the type:

Saab
: 
render
: 
value => { myFunction(value, item.type); }

Any ideas what I could be doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    Think i might have resolved it, required back ticks for the value

    render: 
    `(value) => { 
            myFunction(value, ${item.type})
     }`
    

  2. Not sure why you are expecting item.type to be replaced in the output, but it’s probably working the way you want it…

    Ie if I add a simple myFunction with the correct signature, it will log out the correct value of item.type

    const cars = [
      {name: "Saab", type: "car1" }, 
      {name: "Volvo", type: "car2" }, 
      {name: "BMW", type: "car3"}
    ];
    
    const dataTest = cars.map(item => {
      const renderData = {}
    
      renderData[item.name] = {
        render: (value) => { 
            myFunction(value, item.type)
          },
      }
      return renderData;
    })
    
    function myFunction(v, t) {
      console.log(`v: ${v}    t: ${t}`);
    }
    
    dataTest[0].Saab.render("foo");
    dataTest[1].Volvo.render("bar");
    dataTest[2].BMW.render("baz");
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search