从多维数组jquery中获取特定数据

时间:2016-05-30 07:53:02

标签: javascript jquery arrays multidimensional-array

我有像这样的数组数据

 [{id:1, cost:20, range:15} {id:2, cost:30, range:13}]

我想像这样使用jquery制作数组数据

cost : [20, 30]
range : [15, 13]

请告诉我该怎么做。

2 个答案:

答案 0 :(得分:2)

使用 forEach 方法迭代并将值推送到数组

$notifications = \DB::table('notifications')
            ->select(\DB::raw("notifications.uuid , images.local_path as title_image" ))
            ->leftJoin('images',function ($join) {
                $join->on('images.owner_uuid', '=' , 'notifications.uuid') ;
                $join->where('images.relation','=','notification_title') ;
            });

或使用 map() 方法并生成数组

var cost = [],
  range = [];

var data = [{
  id: 1,
  cost: 20,
  range: 15
} ,{
  id: 2,
  cost: 30,
  range: 13
}];

data.forEach(function(v) {
  cost.push(v.cost);
  range.push(v.range);
});

console.log(cost, range);

答案 1 :(得分:0)

您可以使用Array#forEach()和结果对象以及要分组的所需属性的数组。



var array = [{ id: 1, cost: 20, range: 15 }, { id: 2, cost: 30, range: 13 }],
    result = {};

array.forEach(function (a) {
    ['cost', 'range'].forEach(function (k) {
        result[k] = result[k] || [];
        result[k].push(a[k]);
    });
});

console.log(result);




相关问题