将对象路径作为typescript中的参数传递

时间:2017-11-09 16:24:14

标签: javascript arrays angular typescript

我有一个方法用一个数组替换另一个对象。它将按ID搜索并更改所有与指定ID匹配的记录。

我想将此更改为一个通用的,可重用的方法,可以对我传入的任何对象类型以相同的方式操作。(EG:car.idcar.door.idcar.trunkMonkey.id等等。)

我有没有办法传递" element.car.id"路径作为变量进入这个方法?

updateArrayObject(item: any, data: any[]) {
        // Parse all objects in the array, looking for matches by ID
        data.forEach(element => {
            if (element.car.id === item.id) { // <-- Can I pass "element.car.id" into the method somehow?
                // Item ID matches. Replace the item.
                element.car = item;
            }
        });
    }

2 个答案:

答案 0 :(得分:2)

有些程序通过字符串("element.car.id")执行此操作,并在运行时解析路径。不幸的是,它不是类型安全的。

这有点复杂并有其局限性,但它是类型安全的:

function updateArrayObject<T, R>( // ElementType, ReplacementType
    data: T[], // The array
    getter: (element: T) => R, // Getter of the thing that might be replaced
    setter: (element: T, replacement: R) => void, // Setter of the replacement, when appropriate
    keyComparer: (candidate: R, replacement: R) => boolean, // The matching predicate
    replacement: R) { // The replacement

    data.forEach(element => {
        if (keyComparer(getter(element), replacement)) {
            setter(element, replacement);
        }
    });
}

var sample: Element[] = [ /* ... */ ];

// Your car example
updateArrayObject<Element, Car>(
    sample,
    e => e.car,
    (e, r) => { e.car = r },
    (left, right) => left.id === right.id,
    {
        id: 42,
        door: { id: 0, name: 'driver' },
        trunkMonkey: { id: 0, tmName: 'bozo' }
    })

// Your trunkMonkey example
updateArrayObject<Element, TrunkMonkey>(
    sample,
    e => e.car.trunkMonkey,
    (e, r) => { e.car.trunkMonkey = r },
    (left, right) => left.id === right.id,
    {
         id: 0, tmName: 'bozo'
    })

// The various custom types involved.
interface Door { id: number, name: string }
interface TrunkMonkey { id : number, tmName: string }
interface Car {
    id: number,
    door: Door,
    trunkMonkey: TrunkMonkey
}
interface Element {
    car: Car,
    otherElementData: any
}

您也可以研究&#34;功能性镜片&#34;。

答案 1 :(得分:0)

这是您的通用函数,cible可以是cardoor ...:

updateArrayObject(item: any, data: any[], cible) {
        // Parse all objects in the array, looking for matches by ID
        data.forEach(element => {
            if (element[cible].id === item.id) { // <-- Can I pass "element.car.id" into the method somehow?
                // Item ID matches. Replace the item.
                element[cible]= item;
            }
        });
    }