简体   繁体   English

typescript - 从数组中的值创建对象

[英]typescript - create object from values in array

let's say I have a model definition like this.假设我有这样的模型定义。

export interface Basicdata {
    materialnumber: number;
    type: string;
    materialclass: string;
}

I furthermore have an array with values, which match exactly the order of the Basicdata model, ie我还有一个包含值的数组,它与 Basicdata 模型的顺序完全匹配,即

["10003084", "S", "CLIP"]

I am searching for a way to create the object from these values in the array.我正在寻找一种从数组中的这些值创建对象的方法。 What I did is creating an empty object and assigning the array values.我所做的是创建一个空对象并分配数组值。

const singleRow = rows[0];

const newBD: Basicdata = {
 materialnumber: 0,
 type: '',
 materialclass: '',  
}


newBD.materialnumber = singleRow[0];
newBD.type = singleRow[1];
newBD.materialclass = singleRow[2];

But surely there is a better, more elegant way to do that, no?但肯定有更好、更优雅的方式来做到这一点,不是吗? I looked into map and reduce but could find a way.我查看了 map 和 reduce,但可以找到方法。

Thank you.谢谢你。

As others have mentioned, use a class so that you can use the spread operator (technically you could create a function that returns an objects that meets the interface Basicdata , but you should use a class)正如其他人所提到的,使用一个类以便您可以使用扩展运算符(从技术上讲,您可以创建一个返回满足接口Basicdata的对象的函数,但您应该使用一个类)

class Basicdata {
  materialnumber: number;
  type: string;
  materialclass: string;

  constructor(materialnumber: string | number, type: string, materialclass: string, ...rest: any) {
    this.materialnumber = typeof materialnumber === "number" ? materialnumber : parseInt(materialnumber);
    this.type = type;
    this.materialclass = materialclass;
  }
}

const rows: [string, string, string][] = [
  ["10003084", "S", "CLIP"],
  ["4324324", "B", "FOUR"],
  ["4444432", "C", "CORN"],
];

const singleRow = rows[0];

const newBD = new Basicdata(...singleRow) ;

Playground link 游乐场链接

The issue with the following solution is that it relies on the order of the object properties being consistent.以下解决方案的问题在于它依赖于对象属性的顺序是否一致。 Is this about what you're looking for?这是关于你要找的东西吗?

const singleRow = [1, "2", "3"];

const newBD: Basicdata = {
    materialnumber: 0,
    type: "",
    materialclass: "",
};

Object.keys(newBD).map((key, index) => {
    newBD[key] = singleRow[index]
});

If not, you could make a class as others have said, or you can make a helper function likes this, if it would help with your use case.如果没有,你可以像其他人所说的那样创建一个类,或者你可以像这样创建一个辅助函数,如果它对你的用例有帮助的话。

const addProps = (arr) => {
    const newObj = {
        materialnumber: arr[0],
        type: arr[1],
        materialclass: arr[2],
    };

    return newObj
};

addProps(singleRow)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM