使用javascript或angular js变换数组

时间:2017-10-22 16:55:33

标签: javascript angularjs arrays json

我需要使用angularjs / javascript将下面的Json数组转换为另一个数组,如下所述。

Input Array = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}]

Output Array: [{"Name":"123", "Type1":"24", "Type2":"25"}, {"Name":"124", "Type1":"26", "Type2":"27"}

3 个答案:

答案 0 :(得分:1)

我会用reduce函数来解决这个问题我也在内部为你添加了一些评论:

let inputArray = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];
// and do reduce function on it
inputArray.reduce((prevVal, currVal, index) => {

    // first check if there's Name in already
    if (prevVal.find(x => x.Name === currVal.Name)) {

        // if there's a Name same as current element use new type as a key and add Total
        prevVal.find(x => x.Name === currVal.Name)[currVal.Type] = currVal.Total;
    } else {

        // in case there's no Name then just create object with it
        prevVal.push({
            Name: currVal.Name,
            [currVal.Type]: currVal.Total
        });

        }

        return prevVal;
    }, []);

这里的小提琴: https://jsfiddle.net/pegla/s9hwbth4/

答案 1 :(得分:0)

你不需要angularjs来做到这一点。你可以使用简单的javascript for block来做到这一点。请参阅附件代码。最好,

let input = [{"Name":"123", "Type": "Type1", "Total":"24"}, {"Name":"123", "Type": "Type2", "Total":"25"}, {"Name":"124", "Type": "Type1", "Total":"26"}, {"Name":"124", "Type": "Type2", "Total":"27"}];

let output = [];

for(let i=0; i<input.length-1;i++){
    output.push({
        "Name":input[i].Name,
        "Type1":input[i].Total,
        "Type2":input[i+1].Total,
      });
      i++;
}

console.log(output);

答案 2 :(得分:0)

您所要做的就是根据Name从原始列表中获取唯一对象。

&#13;
&#13;
var obj = [{
        "Name": "123",
        "Type": "Type1",
        "Total": "24"
    },
    {
        "Name": "123",
        "Type": "Type2",
        "Total": "25"
    },
    {
        "Name": "124",
        "Type": "Type1",
        "Total": "26"
    },
    {
        "Name": "124",
        "Type": "Type2",
        "Total": "27"
    }
];
var getIndex = function(list, property, object) {
    for (var i = 0; i < list.length; i++) {
        if (list[i][property] == object[property]) {
            return i;
        }
    }
    return -1;
}
var result = [];
for (var i = 0; i < obj.length; i++) {
/*  Call getIndex to return the index of element in the result and add the type name property */
    var index = getIndex(result, 'Name', obj[i]);
    if (index != -1) {
        result[index][obj[i].Type] = obj[i].Total;
    } else {
        var newObj = {};
        newObj.Name = obj[i].Name;
        newObj[obj[i].Type] = obj[i].Total;
        result.push(newObj);
    }
}
console.log(result);
&#13;
&#13;
&#13;