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

标签 javascript node.js

我有两个对象数组。

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));

关于javascript - 结合两个函数来处理对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57766478/

相关文章:

javascript - JSON.stringify 时,Json 到 ASP.NET MVC Controller 参数为 null

javascript - 如何在javascript中模拟输入元素的真实点击

node.js - `[Function]` 和 `[Function: Object]` - 有什么区别?

templates - 熨斗实现 WP 样式板

javascript - 更改按钮值和颜色

javascript - 使用javascript从日期时间中提取时间

node.js - NPM package.json 文件的主要用途是什么?

node.js - 谷歌云发布/订阅功能在查询 firestore 时给出 "The requested snapshot version is too old"

javascript - Node.js - 如何使用 promise 测试 HTTPS 请求

javascript - window.location.reload 完成了吗?