繁体   English   中英

将对象数组与 JavaScript 中的数组进行比较

[英]Compare Array Of Objects To Array In JavaScript

所以,我在为客户做项目时遇到了这个问题。 基本上我有一个包含对象的数组和一个值数组,我需要用对象填充数组,数组中的每个项目都有对象。 说起来有点令人困惑,但这是代码和输出应该是什么:

// The Array, and the array with objects
var worksheet   = [{"student_name": "Test 1", "file": "some_file_name.txt"}, {"student_name": "Test 3", "file": "file": "some_file_name.txt"}]
var data        = {"student_names": ["Test 1", "Test 2", "Test 3", "Test 4"]}

这里的想法是遍历 data.student_names 并附加不在工作表中的每个学生,

// Output Should Be:
var worksheet = [
    {"student_name": "Test 1", "file": "some_file_name.txt"},
    {"student_name": "Test 3", "file": "some_file_name.txt"},
    {"student_name": "Test 2", "file": ""}, // This wasn't here
    {"student_name": "Test 4", "file": ""}, // This wasn't here
]

 const worksheet = [ { 'student_name': 'Test 1', 'file': 'some_file_name.txt' }, { 'student_name': 'Test 3', 'file': 'some_file_name.txt' } ] const data = { 'student_names': [ 'Test 1', 'Test 2', 'Test 3', 'Test 4' ] } const result = data['student_names'] .map(value => { let record = worksheet.filter(item => item['student_name'] === value) let file = record.length === 0 ? '' : record[0].file return { 'student_name': value, 'file': file } } ) console.log(result)

概念

遍历data.student_names并检查名称是否存在于工作表中。 如果找到,将学生对象放入foundArr 否则,将带有空文件的学生姓名存储在notFoundArr中。 最后,将两个数组连接在一起以获得结果。

代码

 const worksheet = [{"student_name": "Test 1", "file": "some_file_name.txt"}, {"student_name": "Test 3", "file": "some_file_name.txt"}]; const data = {"student_names": ["Test 1", "Test 2", "Test 3", "Test 4"]}; let foundArr = []; let notFoundArr = []; data.student_names.forEach(s => { let studentFound = worksheet.find(ws => ws.student_name === s); if (studentFound !== undefined){ foundArr.push(studentFound); } else { notFoundArr.push({"student_name": s, "file":""}); } }); let result = foundArr.concat(notFoundArr); console.log(result);

暂无
暂无

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

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