簡體   English   中英

使用javascript更改JSON結構

[英]change JSON structure using javascript

這是我的代碼..

var result = data.map(function(item){
    return {
        category:item.category,
        key:item.key,
        value:item.value
    }
});
console.log(result);

這是在控制台打印出來的東西..

Array[4]
0: Object
category: "common"
key: "Food"
value: "food"

1: Object
category: "welcome"
key: "title"
value: "Welcome..."

2: Object
category: "welcome"
key: "app_description"
value: "In this App "

3: Object
category: "welcome"
key: "select_location"
value: "Select Location"

這就是我想要實現的目標

{
    common:{
        "Food" : "food"
    },
    welcome:{
        title : Welcome...,
        app_description : "In this App",
        select_location : "Select Location"

    }
}

這是我正在嘗試的代碼。但它不起作用..

return {
    item.category:{
        item.key:item.value;                    
    }

誰能幫我這個? 我不想使用GSON或任何其他第三方JS。如何才能使用核心JS完成這項工作?

首先,你想要的結果是一個對象,而不是一個數組。 所以你不能使用只能將一個數組映射到另一個數組的.map()

你想要.reduce()

var result = data.reduce(function (result, item) {
    // Create the object the first time it arrives
    result[item.category] = result[item.category] || {};
    // Add the field
    result[item.category][item.key]=item.value;
    // Return the resulting object
    return result;
}, {});
console.log(result);

.reduce()的縮減函數需要兩個(另外兩個可選)參數。 累積結果當前項目 返回的值是在其上處理當前項目之后的結果。

.reduce()的第二個參數(第一個是縮減函數)是初始值 ,該值將作為第一次迭代的result傳遞。

Array.prototype.reduce()來救援。

var result = data.reduce(function (previousValue, currentValue) {
    previousValue[currentValue.category] = previousValue[currentValue.category] || {};
    previousValue[currentValue.category][currentValue.key] = currentValue.value;
    return previousValue;
}, {});

你也可以嘗試:

var data = [
    {
        category: "common",
        key: "Food",
        value: "food"
    },
    {
        category: "welcome",
        key: "title",
        value: "Welcome..."
    },
    {
        category: "welcome",
        key: "app_description",
        value: "In this App "
    },
    {
        category: "welcome",
        key: "select_location",
        value: "Select Location"
    }
];
var obj = {};
for (var i in data) {
    if(!obj[data[i].category]){
        obj[data[i].category] = {};
    }
    obj[data[i].category][data[i].key] = data[i].value;
}
console.log(obj);

暫無
暫無

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

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