Home > Blockchain >  Compare Array Of Objects To Array In JavaScript
Compare Array Of Objects To Array In JavaScript

Time:07-06

So, I ran into this problem while working on a project for a client. Basically I have an array with objects and an array of values, and I need to fill the array with objects, with objects for every item in the array. It's a little confusing to say, but here's the code and what the output should be:

// 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"]}

The idea here, is to loop through data.student_names and append every student that isn't in worksheet,

// 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
]

CodePudding user response:

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)

CodePudding user response:

Concept

Iterate through the data.student_names and check if the name exists in the worksheet. If found, put the student object in foundArr; otherwise, store the student name with empty file in notFoundArr. Lastly, concatenate both arrays together to get the result.

Code

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

  • Related