繁体   English   中英

结合两个函数来处理对象数组

[英]Combining two functions for working with an array of objects

我有两个对象数组。

const details = [
    {
        ciphertext: 1234,
        buyer: {
            op_timezone: 7689,
            op_city: 'Name1',
        },
        assignment_info: { 
            info: {
                end_data: 1456,
                start_date: 2389,
            }
        }
    },
    {
        ciphertext: 5678,
        buyer: {
            op_timezone: 4568,
            op_city: 'Name2',
        },
        assignment_info: { 
            info: {
                end_data: 3467,
                start_date: 8753,
            }
        }
    },
];

const jobIds = [
    {
        id: 1,
    },
    {
        id: 2,
    },
];

我需要组合两个数组并从每个对象中获取assignment_info.info和buyer字段。

function getDetailsBuyersWithJobIds(jobIds, details) {
    return jobIds.map((item, index) => ({
        ...item,
        ...details[index].buyer,
    }));
};

function getDetailsAssignmentInfosWithJobIds(jobIds, details) {
    return jobIds.map((item, index) => ({
        ...item,
        ...details[index].assignment_info.info,
    }));
};

问题是,如何将两个功能组合成一个?

没有重复的功能,因为它们执行相同的操作。

您可以执行通用映射函数并将其传递给getter函数,该函数将能够获取正确的数据,但不确定它是否有助于全局可读性。

你觉得怎么样?

 const genericMapper = (getter) => (item, index) => ({ ...item, ...getter(details[index]), }); function getDetailsBuyersWithJobIds(jobIds, details) { return jobIds.map(genericMapper(it => it.buyer)); }; function getDetailsAssignmentInfosWithJobIds(jobIds, details) { return jobIds.map(genericMapper(it => it.assignment_info.info)); }; const details = [ { ciphertext: 1234, buyer: { op_timezone: 7689, op_city: 'Name1', }, assignment_info: { info: { end_data: 1456, start_date: 2389, } } }, { ciphertext: 5678, buyer: { op_timezone: 4568, op_city: 'Name2', }, assignment_info: { info: { end_data: 3467, start_date: 8753, } } }, ]; const jobIds = [ { id: 1, }, { id: 2, }, ]; console.log(getDetailsBuyersWithJobIds(jobIds, details)); console.log(getDetailsAssignmentInfosWithJobIds(jobIds, details)); 

您可以根据类似的条件在返回对象上添加值

 const details = [{ciphertext: 1234,buyer: {op_timezone: 7689,op_city: 'Name1',},assignment_info: {info: {end_data: 1456,start_date: 2389,}}},{ciphertext: 5678,buyer: {op_timezone: 4568,op_city: 'Name2',},assignment_info: {info: {end_data: 3467,start_date: 8753,}}},]; const jobIds = [{id: 1,},{id: 2,},]; function getDetails(jobIds, details, props = { getBuyer: true }) { return jobIds.map((item, index) => ({ ...item, ...(props.getBuyer && { ...details[index].buyer }), ...(props.getAssignment && { ...details[index].assignment_info.info }) })); }; console.log(getDetails([1], details, { getBuyer: true })) console.log(getDetails([1], details, { getAssignment: true })) 

这里props = { getBuyer: true}用于设置默认值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM