transponse和转换数组与映射

时间:2018-01-18 11:49:55

标签: javascript arrays mapping

如何使其生成所需的输出?

另外,如果没有中间分配,是否值得/可能使它成为一行?

const matches = 
[
  {id: 1, bd: "a"},
  {id: 2, bd: "b"},
  {id: 4, bd: "e"},
  {id: 3, bd: "c"}
];
// ideal output would be { ids: [1,2,4,2], bds: ["a", "b", "e", "c"] }
// but I could only get to [[1,2,4,3],["a","b","e","c"]]

    let matchArgs;
    matchArgs = matches.map((match) => 
             [match.id, match.bd]);

    console.log("1.", matchArgs);

    matchArgs = matchArgs[0].map((match, i) => matchArgs.map(row => row[i]));

    console.log("2:", matchArgs)

Runnable code

4 个答案:

答案 0 :(得分:2)

您可以使用reduce()方法返回对象。



const matches =  [
  {id: 1, bd: "a"},
  {id: 2, bd: "b"},
  {id: 4, bd: "e"},
  {id: 3, bd: "c"}
];

const result = matches.reduce((r, {id, bd}) => {
  r.ids = (r.ids || []).concat(id)
  r.bds = (r.bds || []).concat(id)
  return r;
}, {})

console.log(result)




答案 1 :(得分:1)

使用reduce

var output = matches.reduce((a, c) => (
   a.ids.push( c.id ), 
   a.bds.push( c.bd ), a
), {
  ids:[],
  bds:[]
});

<强>演示

&#13;
&#13;
var matches = 
[
  {id: 1, bd: "a"},
  {id: 2, bd: "b"},
  {id: 4, bd: "e"},
  {id: 3, bd: "c"}
];

var output = matches.reduce((a, c) => (a.ids.push(c.id), a.bds.push(c.bd), a), {
  ids:[],
  bds:[]
});

console.log(output);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用.reduce()

var result = matches.reduce((obj, currentObj) => {
  obj.ids.push(currentObj.id);
  obj.bds.push(currentObj.bd);
  return obj;
}, {ids: [], bds: []});

<强>演示:

const matches = 
[
  {id: 1, bd: "a"},
  {id: 2, bd: "b"},
  {id: 4, bd: "e"},
  {id: 3, bd: "c"}
];

var result = matches.reduce((obj, currentObj) => {
	obj.ids.push(currentObj.id);
  obj.bds.push(currentObj.bd);
  return obj;
}, {ids: [], bds: []});

console.log(result);

答案 3 :(得分:0)

您可以通过迭代密钥并在必要时为所需的值数组构建新属性,而无需事先知道密钥,从而使用动态方法。

如果没有必要,您可以省略+ 's'来生成密钥。

var matches = [{ id: 1, bd: "a" }, { id: 2, bd: "b" }, { id: 4, bd: "e" }, { id: 3, bd: "c" }],
    result = matches.reduce(
        (r, o) => (Object.keys(o).forEach(k => (r[k + 's'] = r[k + 's'] || []).push(o[k])), r),
        {}
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }