返回键选择的修改对象的数组

时间:2019-04-10 18:45:00

标签: javascript arrays json

我有一个用于表行的对象数组:

//ex.h
#include <vector>
using intVec = std::vector<int>;
struct ex
{
    intVec& getVal();
};

//ex.cpp    
static intVec s_val = { 1, 4, 0, 2, 3 };

intVec& ex::getVal()
{
    assert(s_val.size() == 5);
    return s_val;
}

和列的meta

let data = [{name: 'some', date: 1553187727592, user: 'me'},
{name: 'some', date: 1553187727592, user: 'me'},
{name: 'some', date: 1553187727592, user: 'me'}]

我需要函数generateTableRows(data,columns)返回修改后的对象的新数组。每个对象仅包含键及其在meta列中的值,如果使用了修饰符,则使用从回调返回的默认值覆盖默认值。

const columns = [
    {
      id: 'name',
      accessor: 'name',
      label: 'file name',
      numeric: false,
      sortable: true
    },
    {
      id: 'date',
      label: 'created (date)',
      accessor: 'date',
      modifier: value => {
        let date = new Date(value);
        let day = date.getDate();
        let monthIndex = date.getMonth();
        let year = date.getFullYear();
        let hour = date.getHours();
        let minutes = date.getMinutes();
        return `${day}.${monthIndex}.${year} ${hour}:${
          minutes.toString().length <= 1 ? '0' + minutes : minutes
        }`;
      },
      numeric: false,
      sortable: true
    }

1 个答案:

答案 0 :(得分:3)

您可以使用Map作为所需的修饰符,然后使用新属性映射对象。

var columns = [{ id: 'name', accessor: 'name', label: 'file name', numeric: false, sortable: true }, { id: 'date', label: 'created (date)', accessor: 'date', modifier: value => { let date = new Date(value); let day = date.getDate(); let monthIndex = date.getMonth(); let year = date.getFullYear(); let hour = date.getHours(); let minutes = date.getMinutes(); return `${day}.${monthIndex}.${year} ${hour}:${minutes.toString().length <= 1 ? '0' + minutes : minutes}`; }, numeric: false, sortable: true }],
    data = [{ name: 'some', date: 1553187727592, user: 'me' }, { name: 'some', date: 1553187727592, user: 'me' }, { name: 'some', date: 1553187727592, user: 'me' }],
    modifiers = columns.reduce((m, { id, modifier }) => m.set(id, modifier), new Map),
    result = data.map(o => Object.assign(...Object
        .entries(o)
        .map(([k, v]) => ({ [k]: (modifiers.get(k) || (v => v))(v) }))
    ));

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