简体   繁体   English

如何从一个对象创建一个字符串数组,其中各个键的值是单独的字符串数组?

[英]How do I create an array of strings from an object where the values of individual keys are separate arrays of strings?

I'm trying to gather all errors in an err object and populate them into this.errors in order to display them. 我试图将所有错误收集到一个err对象中,并将其填充到this.errors中以显示它们。

err object : err对象

err = {
  "name": [
    "Item name is required.",
    "Item name must be at least 4 chars"
  ],
  "rate": [
    "Item Rate is should be a number.",
    "Item rate should be between 10 and 1000"
  ],
  "category": ["Item Category is required"]
}

As you can see, err is an object where the values of individual keys are arrays of strings. 如您所见,err是一个对象,其中各个键的值是字符串数组。 To gather the error strings into a separate this.errors array, I could simply perform: 要将错误字符串收集到单独的this.errors数组中,我可以简单地执行以下操作:

 if (err && err.number)  {
   err.number.forEach(e => {
     this.errors.push(e);
   });
 }

if (err && err.number)  {
   err.rate.forEach(e => {
     this.errors.push(e);
   });
 }

 if (err && err.number)  {
   err.category.forEach(e => {
     this.errors.push(e);
   });
 }

But I will need to repeat these lines of code in many places of my app. 但是我需要在我的应用程序的许多地方重复这些代码行。

I want to place these code in a functionl as: 我想将这些代码放在如下的functionl中:

populateErrors(err) {
    err.forEach(error => {
          this.errors.push(error);
    });
}

// and call it
this.populateErrors(err);

OR 要么

populateErrors(err, keys[]) {
    err.forEach(error => {
          this.errors.push(err.keys[1]);
    });
    //...
}

// and call it
populateErrors(err, ['name', 'rate', 'category'])

and display them in my template: 并将它们显示在我的模板中:

<div class="row" *ngIf="errors && errors.length">
    <div class="col-md-12">
        <div class="alert alert-danger alert-dismissible">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                <ol *ngFor="let err of errMsg">
                    <li>{{ err }}</li>
                </ol>
        </div>
    </div>
</div>

What might the function look like? 该函数是什么样的?

You can use a map reduce . 您可以使用map reduce

 const err = { "name": [ "Item name is required.", "Item name must be at least 4 chars" ], "rate": [ "Item Rate is should be a number.", "Item rate should be between 10 and 1000" ], "category": ["Item Category is required"] } const arr = Object.keys(err) .map(k => err[k]) .reduce((acumm, el) => acumm.concat(el), []); console.log(arr) 

We're combining Object.keys a native function that allow you to obtain the keys of an object with map and reduce . 我们将Object.keys组合成一个本机函数,使您可以使用mapreduce来获取对象的键。

["name", "rate", "category"].map(...

The map method creates a new array with the results of calling a function for every array element. map方法创建一个新数组,并为每个数组元素调用一个函数。 So, I am returning the value of the property itself. 因此,我将返回属性本身的值。

[[ "Item name...", "Item name..." ], ["Item Rate...", "Item rate"], ["Item Category..."]].reduce(...

The reduce method reduces the array to a single value. reduce方法将数组reduce为单个值。 So I am concatenating all the values in a single array. 所以我将所有值串联在一个数组中。

You can use the map function coupled with a loop over the properties : 您可以将map函数与属性循环结合使用:

for (let prop in this.err) {
    this.errors = this.errors.join(
        this.err[prop].map(el => ({el}));
    );
}

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

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