在对象数组中为每个项目添加对象键

3

我有一个负载从这样的端点返回:

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

如何最好地为dates数组中的每个项目附加id,以便结果如下:

[
    { id: 'someId', date: '2017-11-11' },
    { id: 'someId', date: '2017-12-11' },
    { id: 'anotherId', date: '2017-09-11' },
    { id: 'anotherId', date: '2017-10-11' },
]

我尝试了类似这样的东西:
let history = [];
charges.map(charge => (
    charge.dates.map((date) => (
        history.concat({
            id: charge.payerCode,
            date: date,
        })
    ))
));

但是我所使用的范围中并没有定义历史。

我知道可能有更好的方法来解决这个问题,但我似乎无法理解它。

任何帮助都将不胜感激!

谢谢!


您希望输出什么? - Evan Trimboli
请告诉我您期望的输出示例是什么? - solimanware
已将所需输出添加到问题中。抱歉! - Chris Frank
你是否试图让“history”包含你想要的输出? - 4castle
1
“map”不是在这里使用的正确工具,因为您的输出数组可能不会与输入数组具有相同数量的元素。正如答案中提出的那样,“reduce”是要使用的工具。 - sp00m
6个回答

3
你可以使用 Array#reduce 方法来连接所有对象,并创建包含日期的数组。

let charges = [{ id: 'someId', dates: ['2017-11-11', '2017-12-11'] }, { id: 'anotherId', dates: ['2017-09-11', '2017-10-11'] }],
    result = charges.reduce((r, { id, dates }) => r.concat(dates.map(date => ({ id, date }))), []);

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

Edge版本,它可以防止(这可能是Edge内部的一个错误)

SCRIPT5113: Use before declaration
result = charges.reduce((r, { id, dates }) => r.concat(dates.map(date => ({ id, date }))), []);
                                                                            ^

const
    charges = [{ id: 'someId', dates: ['2017-11-11', '2017-12-11'] }, { id: 'anotherId', dates: ['2017-09-11', '2017-10-11'] }],
    result = charges.reduce((r, a) => r.concat(a.dates.map(d => ({ id: a.id, date: d }))), []);

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


3

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

function flatten(charges) {    
  return charges.reduce((p, {id, dates}) => 
           (dates.forEach(date => p.push({id, date})), p), []);    
}

console.log(flatten(charges))


1
一种简单的命令式解决方案是:

const history = [];
for (const { payerCode, dates } of charges) {
  for (const date of dates) {
    history.push({ id: payerCode, date });
  }
}

1
你可以像这样使用Array#reduceArray#concat结合起来:

const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];

var r = charges.reduce(function(acc, obj) {
  return acc.concat(obj.dates.map(function(date) {
    return {
      id : obj.id,
      date : date
    };
  }))
}, []);

console.log(r);


0
$(document).ready(function(){
    const charges = [
    {
        'id': 'someId',
        'dates': ['2017-11-11', '2017-12-11'],
    },
    {
        'id': 'anotherId',
        'dates': ['2017-09-11', '2017-10-11'],
    },
];
var temp={};
var finalArray = [];
for(ch in charges){
    for(dt of charges[ch]['dates']){
        temp.id = charges[ch]['id'];
        temp.date =dt;
        finalArray.push(temp);
        temp={};
    }
}
console.log(JSON.stringify(finalArray));
});

0
尝试使用 Array#reduce 重新创建数组,并使用 Array#forEach 迭代内部数组。

const charges = [{'id': 'someId', 'dates': ['2017-11-11', '2017-12-11'],}, { 'id': 'anotherId','dates': ['2017-09-11', '2017-10-11'],},];

var res = charges.reduce(function(a,b){
b.dates.forEach(function(n){
a.push({id:b.id,dates:n})
})
return a;
},[])

console.log(res)

ES6

const charges = [{'id': 'someId', 'dates': ['2017-11-11', '2017-12-11'],}, { 'id': 'anotherId','dates': ['2017-09-11', '2017-10-11'],},];

var res = charges.reduce((a,b) =>(b.dates.forEach(d=>a.push({id:b.id,dates:d})),a),[])

console.log(res)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接