选择对象json中列的值,然后将其转换为数组AngularJs

时间:2016-02-23 09:44:05

标签: angularjs json

这是我的对象我想选择数量和类型的值我不知道如何制作一个矩阵然后将每个值放在martix单元格中是AngularJs中的一个begginer,谢谢

[
    {
        id: 15,
        nom: "azerty",
        type: "azerty",
        quantity: 456,
        prix: 25296
    },
    {
        id: 21,
        nom: "sdqs",
        type: "qsdqsd",
        quantity: 102,
        prix: 52
    }
]

4 个答案:

答案 0 :(得分:0)

你想要这样的东西:

var initialObject = [
 {
  id: 15,
 nom: "azerty",
 type: "azerty",
   quantity: 456,
 prix: 25296
},
{
 id: 21,
 nom: "sdqs",
  type: "qsdqsd",
 quantity: 102,
 prix: 52
 }
 ];

var newArray = {};

var createNewArray = function() {
    angular.forEach(initialObject, function(value, key) {
       newArray.push(value.quantity);
       newArray.push(value.type);
    })
}

//Should produce {456, azerty, 102, qsdqsd}

因此,如果您只想要一个quantity数组,只需将newArray更改为quantity,然后删除newArray.push(value.type);。与type类似的事情。

答案 1 :(得分:0)

试试这个

var x = [
    {
        id: 15,
        nom: "azerty",
        type: "azerty",
        quantity: 456,
        prix: 25296
    },
    {
        id: 21,
        nom: "sdqs",
        type: "qsdqsd",
        quantity: 102,
        prix: 52
    }
];

var type = [];
var quantity = [];

x.forEach(function(item, index) {
    type.push(item.type)
    quantity.push(item.quantity)
    if(index == x.length-1){
        console.log("type: ",type);    //type: ['azerty','qsdqsd']
        console.log("quantity: ",quantity);    // quantity : [456,102]
    }
})

// once forEach is done you'll have type=[azerty,qsdqsd]  and quantity = [456,102]

答案 2 :(得分:0)

看来你的问题与AngularJS本身无关。您可以使用lodashunderscore转换数据。 这是一个使用lodash构建的示例(顺便说一句,我添加了一个数组元素来显示groupBy的工作原理):

var docs = [
    {
        id: 15,
        nom: "azerty",
        type: "azerty",
        quantity: 456,
        prix: 25296
    },
    {
        id: 21,
        nom: "sdqs",
        type: "qsdqsd",
        quantity: 102,
        prix: 52
    },
    {
        id: 22,
        nom: "sdqs",
        type: "qsdqsd",
        quantity: 99,
        prix: 52
    }
];

var newDocs = _.map(docs, function(x) {return {type: x.type, quantity: x.quantity};});
var result = _.groupBy(newDocs, 'type');

console.log(result);

输出如下:

{"azerty":[{"type":"azerty","quantity":456}],"qsdqsd":[{"type":"qsdqsd","quantity":102},{"type":"qsdqsd","quantity":99}]} 

不确定您使用的是哪种图表库以及它期望的输入,但是使用lodash,您肯定能够以任何可能的形式对数据进行整形。

<强>更新

顺便说一句,如果你稍微改变地图功能,你可以将type-&gt;数量映射作为数组(不要复制我的代码风格:)):

var newDocs = _.map(docs, function(x) {var tmp = {}; tmp[x.type] = x.quantity; return tmp;});

输出如下:

[{"azerty":456},{"qsdqsd":102},{"qsdqsd":99}] 

答案 3 :(得分:0)

首先你好你拥有的是一个对象数组,所以我认为你不需要创建两个其他数组,最后有3个数组。 / p>

假设我们将对象保留在您的问题上,并将其命名为 myData ,我们有

如果您想记录类型&amp;数量值

myData.forEach(function(item) {
    console.log(item.type+'  +item.quantity);
})

或将值显示在您的html模板中:

<table>
<tr ng-repeat="item in myData">
  <td>
     {{item.type}}
  </td>
  <td>{{item.quantity}}</td>
</tr>

希望有所帮助,祝你好运。