2

I am trying to use map function to transform property type.

class A {... }
class B {... }

var var1 = [{path:"aa",comp:"A"},{path:"b",comp:"B"}];
var var2 = var1.map(function(obj){ 
   var rObj = {path: obj.path, component: A};
   return rObj;
});

The above code will return to var2

[{path:"aa",comp:A},{path:"b",comp:A}]

What I need is

[{path:"aa",comp:A},{path:"b",comp:B}]

How can I achieve this purpose?

1 Answer 1

3

You're trying to map between a class name (as string) to the actual class.
You can just maintain a mapping object like so:

class A { ... }
class B { ... }

var nameToClassMapping = {
    A: A,
    B: B
};

var var1 = [{ path: "aa", comp: "A" }, { path: "b", comp: "B" }];
var var2 = var1.map(function(obj) { 
    var rObj = { path: obj.path, component: nameToClassMapping[obj.comp] };
    return rObj;
});

Code in playground

Sign up to request clarification or add additional context in comments.

4 Comments

I ran the code and it returned the expected result. Check the link to playground in my answer (just added it)
If class A and B is define in the same file it works as expected. But if the class is an imported one using import {A,B} from ... then the component property showed undefined. Why is so?
are you sure that the classes were loaded? if you do console.log(A, B) after the import what do you get?
My bad. I mismatched property name and type in nameToClassMapping . Thanks you so much for your patience with me. It works great.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.