从一个对象数组中,返回新数组中的键

时间:2018-03-26 18:07:39

标签: javascript arrays javascript-objects

我有一个对象数组,必须在新数组中返回键execute_many:     此功能采用以下格式的狗阵列:

insert_query = "INSERT INTO smallUsers values (?,?,?)"
to_cursor.executemany(insert_query, from_cursor.fetchall())

它应该返回所有狗的所有小狗的数组:

while True:
    current_data = from_cursor.fetchmany(100)
    if not current_data:
        break
    to_cursor.exectutemany(insert_query, current_data)
    sqlite_conn.commit()
sqlite_conn.commit()

到目前为止,这是我的代码:

puppies

它将名称添加到解决方案中,但在[ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ]

之间返回它们
['Fluffy', 'Doggo', 'Floof', 'Biscuits', 'Mary']

我已经在this帖子中看到了我的解决方案,所以我相信我不会走得太远,但无法弄清楚我做错了什么。谁能帮我吗?提前谢谢。

5 个答案:

答案 0 :(得分:2)

使用spread syntax将项目推送到数组中:



const dogs = [{"breed":"Labrador","puppies":["Fluffy","Doggo","Floof"]},{"breed":"Rottweiler","puppies":["Biscuits","Mary"]}];

const collectPuppies = (dogs) => [].concat(...dogs.map(({ puppies }) => puppies));

console.log(collectPuppies(dogs));




另一个选择是让小狗获得Array.map(),并通过传播到Array.concat()来平展结果:



React.Children.map




答案 1 :(得分:1)

你可以结束。

const dogs = [ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ]

const collectPuppies = dogs =>
    dogs.map(d => d.puppies).reduce((a,b) => a.concat(b), []);
  
console.log(collectPuppies(dogs));

答案 2 :(得分:1)

你只需要reduce的Array.prototype。

x=[ {breed: 'Labrador', puppies: ['Fluffy', 'Doggo', 'Floof'] }, {breed: 'Rottweiler', puppies: ['Biscuits', 'Mary'] } ] ;

var result=x.reduce((y,e)=>y.concat(e.puppies),[]);

console.log(result);

答案 3 :(得分:1)

Array.prototype.push会将每个参数都推送到数组,而不是每个参数的各个数组元素。

更正代码的最简单方法是将push替换为concat

  

concat()方法用于合并两个或多个数组。

function collectPuppies(dogs) {
   let solution = [];
   for (let i=0; i < dogs.length; i++){
       solution = solution.concat(dogs[i].puppies);
   }
   return solution;
}

答案 4 :(得分:1)

在对象数组中,小狗也是一个数组。所以你要在数组中添加一个数组。而不是:

solution.push(dogs[i].puppies);

您需要遍历小狗阵列并将每只小狗分别添加到解决方案阵列中。不是将'puppies'字段添加到解决方案数组中,而是为每个对象循环遍历puppies数组并将其添加到解决方案数组中。第二个内部循环可以通过在puppies数组上调用forEach()来轻松完成。例如:

dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});

然后最终的功能是:

function collectPuppies (dogs) {
    let solution=[];
    for(let i=0; i<dogs.length; i++){
       dogs[i].puppies.forEach((puppy) => {solution.push(puppy)});
    }
    return solution;
}