0

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
]
1
  • 1
    What code have you written to try and solve the problem? You should add that to the question. Commented Jul 6, 2022 at 10:26

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much, m8! You saved me a lot of trouble!
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.