簡體   English   中英

如何在 javascript 中連接這種類型的 JSON?

[英]How can I concatenate this type of JSON in javascript?

如何連接此 json 以獲得它:

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

每個地址都可以包含一組補碼,這些補碼必須連接起來並用逗號分隔。

ps:我用的是javascript。 P.s2:補碼可以是 null,就像 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 不是 function

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

有一個javascript object,你可以通過ZA8CFDE6331BD59EB2AC96F8911C4B66的鍵將go組合成一些字符串

它看起來像這樣:

const jsonObject = [{...}, {...}, ...]
const complements = [];

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

這只是一個例子。 有很多方法可以做到這一點。

我是如何解決的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM