过滤对象数组以将不同的值转换为新数组

时间:2016-09-03 20:58:21

标签: jquery arrays

我有created a fiddle here我的问题,在下面的一些答案的帮助下。

我有一个对象数组。数组中的单个对象包含:

obj1, obj2, obj3...

其中一个对象的例子是:

{
client_id: "85"
id: 1477
organisation_id: 5
task_project_id: 26
project_name: "Reiciendis adipisci fugiat."
project_description: "Soluta consequatur labore et dolores"
task_description: "Qui sunt at aut."
task_end_time: null
task_start_time: "2016-05-21 09:00:00"
transaction_id: null
}

我想从第一个数组生成一个新的对象数组,其中包含task_project_id的不同条目。新数组应包含以下结构的不同对象:

{
task_project_id: 26
project_name: "Reiciendis adipisci fugiat."
}

我尝试了jQuery.greparray.filterarray.map,但无济于事。我似乎也找不到使用“提取不同对象的数组”作为搜索的例子。有人能指点我一个例子。感谢。

3 个答案:

答案 0 :(得分:2)

这是你想要的吗?检查输出。!

var oldArray = [{
    client_id: "85",
    id: 1477,
    organisation_id: 5,
    task_project_id: 26,
    project_name: "Reiciendis adipisci fugiat.",
    project_description: "Soluta consequatur labore et dolores",
    task_description: "Qui sunt at aut.",
    task_end_time: null,
    task_start_time: "2016-05-21 09:00:00",
    transaction_id: null
  }, {
    client_id: "86",
    id: 1434,
    organisation_id: 5,
    task_project_id: 22,
    project_name: "Reiciddgdgdfgci fugiat.",
    project_description: "Soluta consequatur labore et dolores",
    task_description: "Qui sunt at aut.",
    task_end_time: null,
    task_start_time: "2016-05-21 09:00:00",
    transaction_id: null
  }],
  newArray;
newArray = oldArray.map(function(obj) {
  return {
    task_project_id: obj.task_project_id,
    project_description: obj.project_description
  }
});

console.log(newArray);

答案 1 :(得分:2)

var b = a.map(function(e) { return { task_project_id: e.task_project_id, project_description: e.project_description } }); 应该可以正常工作:

var seen = {}; // keys = list of unique task project ids
var b = a.filter(function (e) {
  return seen[e.task_project_id] ? false : (seen[e.task_project_id] = true);
});

编辑:通过存储已经遇到的“看到”任务项目ID的列表来过滤掉重复项:

var newArray = (function (a) {
  var seen = {};
  return a.filter(function (e) {
    return seen[e.task_project_id] ? false : (seen[e.task_project_id] = true);
  }).map(function (e) {
    return {
      task_project_id: e.task_project_id,
      project_description: e.project_description
    }
  });
})(oldArray);

全部放在一起:

import threading
import time

def afterThreeSec():
    print("test")
    return

t1 = threading.Timer(3, afterThreeSec)
t1.setName('t1')
t1.start()

print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")
time.sleep(1)
print ("main")

答案 2 :(得分:0)

ES6:

let map = new Map();
a = [{a:1, b:"blue"},{a:1, b:"red"}]
a.map(item=>map.set(item.a, item));
let result = [...map.values()];

结果:

[ { a: 1, b: 'red' } ]