Home > Enterprise >  Extract values from javascript object
Extract values from javascript object

Time:04-06

I am just learning to code so I can become a developer. My interest in JavaScript and I'm needing help to extract values from a JavaScript object and assign values as variables. Please see below:

var members = {
  "Name": "Jake Bayliss",
  "Name": "Daryl Tripp",
  "Name": "Tom McKenzie",
  "Name": "George Bell",
  "Name": "Ally Young"
};

I need to extract the values in this sample data in the following format:

var member1 = "Jake Bayliss";
var member2 = "Daryl Tripp";
var member3 = "Tom McKenzie";
var member4 = "George Bell";
var member5 = "Name":"Ally Young";
var count = //how do I count members?

I have tried to extract the values but I don't think I'm doing it right.

CodePudding user response:

What you need is an array. In this case you have something that should be an array of member names. To get the count you can just get the length of the array with .length. To assign the contents of the array to individual variables you can use array destructuring.

Here's what the code would look like:

const memberNames = [
  "Jake Bayliss",
  "Daryl Tripp",
  "Tom McKenzie",
  "George Bell",
  "Ally Young"
];

const [member1, member2, member3, member4, member5] = memberNames
const count = memberNames.length

This will create an object called members with an arbitrary number of properties, named member1, member2, member3 etc.

const members = memberNames.reduce((previous, memberName, index)=>({
  ...previous,
  ['member' (index 1)]: memberName
}),{})

Result:

{
  member1: 'Jake Bayliss',
  member2: 'Daryl Tripp',
  member3: 'Tom McKenzie',
  member4: 'George Bell',
  member5: 'Ally Young'
}

You'll be able to use the dot operator on members to get each value. E.g. members.member1

  • Related