typescript 如何替换数组中的键标签

ego6inou  于 2023-05-01  发布在  TypeScript
关注(0)|答案(4)|浏览(104)

我在下面的数组中,我需要更新键值为From Apple fruit to Pizza shop,橙子fruit to Kfc shop,Banana fruit to Mcdonald shop,Mango fruit to fries shop,如果任何一个值对超过28个字符,如果它不超过28个字符,它应该保持相同的响应。
例如,在这个测试中,3的值超过了28个字符

[
        {
            "key": "Apple fruit",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Orange fruit",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Banana fruit",
            "value": "3647586/456765/345654/36789876/76"
        },
        {
            "key": "Mango fruit",
            "value": "66789/74657/37485/67543"
        }
    ]

我的准则

this.testItem.push({
      key: testlabel,
      value: testvale,
    });
    console.log(this.testItem);

这个.testItem有我上面提到的值数组,有帮助吗?

kd3sttzy

kd3sttzy1#

你最初的规格有点不清楚,但无论如何。下面是实现您请求的代码:

// Your array - don't add this 
this.testItem = [
        {
            "key": "Testing 1",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 2",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 3",
            "value": "3647586/456765/345654/36789876/76"
        },
        {
            "key": "Testing 4",
            "value": "66789/74657/37485/67543"
        }
    ];

// Add the code below to modify your array `this.testItem`
var hasValueExceeding28Chars = this.testItem.some(item => item.value.length > 28);

this.testItem = hasValueExceeding28Chars
  ? this.testItem.map(item => ({
      key: item.key.replace(/Testing/g, "Test"),
      value: item.value
    }))
  : this.testItem;

console.log(this.testItem);

我们在这里:
1.找出是否有任何值超过28个字符;
1.如果是这样,我们使用the map() function of Javascript将初始值复制到一个新数组中,并相应地修改所有键;
1.如果不是,那么我们保持初始数组。

46qrfjad

46qrfjad2#

代替hello编写代码更改值

testArray.forEach(test => { if(test.value.length > 28 )test.key='hello'});
ktca8awb

ktca8awb3#

testItem = testItem.map(item => {
  if (item.value.length > 28) {
    const num = item.key.substring(item.key.length - 1)
    item.key = `Test ${num}`
  }
  return item
})
kh212irz

kh212irz4#

你可以这样做:

this.testItem =  [
        {
            "key": "Testing 1",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 2",
            "value": "66789/74657/37485/67543"
        },
        {
            "key": "Testing 3",
            "value": "3647586/456765/345654/36789876/76"
        },
        {
            "key": "Testing 4",
            "value": "66789/74657/37485/67543"
        }
    ];

const hasMoreThan28Chars = this.testItem.some(item => item.value.length > 28);

this.testItem = !hasMoreThan28Chars ? this.testItem : this.testItem.map((item) => 
    ({...item, key: item.key.replace("Testing", "Test")})
);

console.log(this.testItem)

相关问题