1

Newbie here and this is a project I'm building to learn. I'm going around in circles so forgive my ignorance please. I'm now not even sure that what I want to do is possible. I also understand that there are probably better ways to achieve my ultimate goal but this is what I have.

I have an array that includes some user input. "participants": [ { "name": "Cristina", "email": "cristina@gmail", "yourPerson": "Richard", "spouseEmail": "Richard@gmail" } ] }

I want to pull the "name" and "youPerson" values and use them as a key:value pair. So name would be the key and yourPerson would be the value.

I thought I could use a forEach but no matter what I do I either get an undefined array or I copy the entire array, not just those two fields.

here is my code at the moment:


  participantArray = [];
  namePlusSpouseArray = [];
  
  submitParticipant() {
    this.participantArray.push(this.participantForm.value);
    console.log(this.participantArray)
    this.createNamePlusSpouseArray();                                             
  }


   createNamePlusSpouseArray() {
    
    this.participantArray.forEach(name  => {
     this.namePlusSpouseArray.push(this.participantArray[name]);
     console.log(this.namePlusSpouseArray)
    });
    }
   

2 Answers 2

2

Not sure if you want a result array of key value pairs, or you want 1 object/map/dictionary/lookup of name -> youPerson

Assuming you want an array containing key value pairs, you can use map

this.namePlusSpouseArray = this.participantArray.map(participant => ({
   [participant.name]: participant.youPerson
});

If you want a lookup of name -> youPerson, the "namePlusSpouseArray" shouldn´t be an array but instead just an object

namePlusSpouseLookup = {};

this.participantArray.forEach(participant => {
    this.namePlusSpouseLookup[participant.name] = participant.youPerson;
});
Sign up to request clarification or add additional context in comments.

Comments

0

The simplest solution is:

const participantArray = {
  "participants": [ { "name": "Cristina", "email": "cristina@gmail", "yourPerson": "Richard", "spouseEmail": "Richard@gmail" } ] };

const createPair = participants => {
  return participants.map(participant => 
  ({ [participant.name]: participant.yourPerson}))
}

console.log(createPair(participantArray.participants));

1 Comment

forgive my ignorance... with this option, the values are hard coded in right? My biggest issue at the moment is getting the values in from a different array which was populated from a form. I'd really like to be able to get just the name and spouses name from the previous array into a new key value pair (I guess a map is the better option now)

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.