【问题标题】:How can I concatenate this type of JSON in javascript?如何在 javascript 中连接这种类型的 JSON?
【发布时间】:2022-01-24 18:10:12
【问题描述】:

如何连接这个 json 来获取它:

complements = ["XYZ 3, CDE TR, AAA 5", "", "NDP 3, DDD FR"]?

每个地址可以包含一组补码,这些补码必须用逗号连接和分隔。

P.s:我正在使用 JavaScript。 P.s2:补码可以为空,就像 JSON 中的第二组一样。

[
    {
        "postalcode": "1234",
        "street": "ABC",
        "number": "1",
        "complement": [
            {
                "type": "B",
                "name": "XYZ",
                "description": "3"
            },
            {
                "type": "C",
                "name": "CDE",
                "description": "TR"
            },
            {
                "type": "D",
                "name": "AAA",
                "description": "5"
            }
        ]
    },
 {
        "postalcode": "444",
        "street": "No complements",
        "number": "5"
    },
    {
        "postalcode": "2222",
        "street": "BBB",
        "number": "2",
        "complement": [
            {
                "type": "E",
                "name": "NDP",
                "description": "3"
            },
            {
                "type": "F",
                "name": "DDD",
                "description": "FR"
            }
        ]
    }
];

我的代码我得到 this.complementsList.forEach 不是函数

getComplement(addressesResponse){
    this.complementsList = JSON.parse(addressesResponse);

    this.complementsList.forEach((item) => {
    Object.defineProperty(item, 'complements', {
        get: function() { 
            return this.complement.map((c) => `${c.name} ${c.description}`).join(', '); }
    })
});

来源:https://salesforce.stackexchange.com/questions/367713/how-to-render-a-json-in-the-same-line-lwc

【问题讨论】:

  • 请将您尝试的代码添加为minimal reproducible example
  • 抱歉,我更新了
  • 还有什么问题?你已经有很多答案了。
  • 我知道...现在我得到无法读取未定义的属性(读取“地图”)

标签: javascript json concatenation


【解决方案1】:

我是怎么解决的:

arr.map((x)=>x.complement != null? (x.complement.map((y)=>y.name+' '+y.description)+"") :'');

【讨论】:

    【解决方案2】:

    拥有一个 javascript 对象,您可以遍历对象的键并将其中一些键组合成字符串

    它看起来像这样:

    const jsonObject = [{...}, {...}, ...]
    const complements = [];
    
    jsonObject.forEach((item) => {
      let complement = item['complement'].reduce((result, currObj) 
         => result += (currObj.name+' '+currObj.description), "");
      complements.push(complement);
    });
    

    这只是一个例子。有很多方法可以做到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-10
      • 1970-01-01
      • 2020-02-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-15
      相关资源
      最近更新 更多