双重for..of循环到单行代码

时间:2017-03-15 23:02:55

标签: javascript

是否可以从下面的代码段制作单行代码?像

这样的东西
Object.values(data).map(v=>v.map(v=>v.id))



let div = document.getElementById("foo");

const data = {
  item: [ {id: 1} ],
  another: [ {id: 3}, {id: 10} ],
} 


let id = Object.values(data);
for(const foo of id){
  for(const bar of foo){
    div.append(bar.id + ", ") //instead div.append should be "return bar.id;"
  }
}

<div id="foo"></div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

请为您的&#39;更大的&#39;测试此代码。阵列。

&#13;
&#13;
let data = {item:[{id:1}],another:[{id:3},{id:10}]},
    result = Object.keys(data).reduce(function(s, a) {
      s.push(data[a].map(v => v.id));
      return s;
    }, []);

    console.log([].concat.apply([], result));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您是否想要压扁生成的数组?在这种情况下,您可以尝试:

Object.values(data).reduce((a, b) => a.concat(b)).map(e => e.id)

<小时/>

演示片段:

&#13;
&#13;
const data = {
  item: [ {id: 1} ],
  another: [ {id: 3}, {id: 10} ]
} 

console.log(
  Object.values(data).reduce((a, b) => a.concat(b)).map(e => e.id)
)
&#13;
.as-console-wrapper { min-height: 100vh; }
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在Question的对象中给出两个属性,你可以使用object destructuring,spread element

const data = {
  item: [ {id: 1} ],
  another: [ {id: 3}, {id: 10} ],
} 

let ids = [...data.item, ...data.another].map(({id}) => id);

console.log(ids);