0

I have the below object where I want to get the name of the first item in the staff array.

const staffObj = {
  "staff":[
    { "name": "tom"},
    { "name": "sam"}
  ]
}

I can do this by doing either

console.log(staffObj['staff'][0]['name'])
console.log(staffObj.staff[0].name)

But what I want to do is is access my object from a variable I create eg

const currentField = 'name'    
const firstITem = ['staff'][currentField ]
console.log(firstITem,staffObj.firstITem)

What is the correct syntax to achieve this?

ak85
  • 4,154
  • 18
  • 68
  • 113

7 Answers7

1

You can't put bits of Javascript source code in a variable like that. You need variables for each part:

const currentType = 'staff';
const currentField = 'name';
console.log(staffObj[currentType][0][currentField]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

You missing [0] in your code. You should use a function for such things. Example:

function firstFtaffField(staffObj, field) {
  return staffObj['staff'][0][field];
}

// Usage
var name = firstFtaffField(staffObj, 'name');
Oleg Imanilov
  • 2,591
  • 1
  • 13
  • 26
0

You can do this if you want to use currentField as a variable. Notice how firstITem[currentField] has currentField which is not in quotes. It is a variable and evaluated by javascript and then applied as property name.

const staffObj = {
  "staff":[
    { "name": "tom"},
    { "name": "sam"}
  ]
};

console.log(staffObj['staff'][0]['name']);
console.log(staffObj.staff[0].name)

const currentField = 'name';   
const firstITem = staffObj.staff[0];
console.log(firstITem[currentField]);
Pankaj Shukla
  • 2,657
  • 2
  • 11
  • 18
0

That is not possible, but you could do something similar by defining firstItem as a function:

const staffObj = {
  "staff":[
    { "name": "tom"},
    { "name": "sam"}
  ]
};

const currentField = 'name';
const firstItem = x => x['staff'][0][currentField];
console.log(firstItem(staffObj))
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You look like you might want something like function!

As a quick note since you seem to be a beginner: Arrow Functions

var get = n => c => c[n]; // function given a nest returns a function given a container returns the nest inside the container
var obj = {
  staff:[
    { name: 'tom' },
    { name: 'sam' }
  ]
};

var getFirst = get(0);
var getStaff = get('staff');

console.log(getFirst(getStaff(obj))); // { name: 'tom }

Of course this is functional programming that relys on composition, so if that doesn't make too much send to you you can instead go with a more familiar imperative version:

var obj = { staff: [ {name:'tom'}, {name:'sam'}]};
var getStaff = obj => obj['staff'];
var getFirst = ary => ary[0];

var staff = getStaff(obj);
var firstStaff = getFirst(staff);

// alternate
//var getFirstStaff = obj => getFirst(getStaff(obj));

console.log(firstStaff);

As you can see there are some similarities between the two, but composition is done in a reversed order with some more advanced techniques(composition, currying). Since you seem to be new to JS I'd suggest doing it the second way so it makes more sense until you understand the first way(which will make thinking in promises a LOT easier)

Robert Mennell
  • 1,954
  • 11
  • 24
0

In JavaScript the someObject.someProperty notation is a shorthand for someObject['someProperty'].

Which means that if you want to have a dynamically calculated property name, you can't use a 'dot' notation, because someObject.someProperty will always be interpreted as someObject['someProperty'] regardless of the fact that someProperty is maybe a valid variable which holds some value of string type.

Also, if you try to use something like someObject."someProperty" you will get Uncaught SyntaxError: Unexpected string, because that isn't a valid JS syntax.

-1

There is no such syntax. The only way you could do it using eval:

const staffObj = {
  "staff":[
    { "name": "tom"},
    { "name": "sam"}
  ]
};
const currentField = 'name';
const firstItem = ".staff[0]." + currentField;
console.log(eval("staffObj" + firstItem));

If currentField is actually variable, then you will have to change firstItem as well every time you change the currentField.

Viacheslav
  • 84
  • 1
  • 5
  • This is what `eval` should **not** be used for. – Bergi Jun 01 '17 at 22:18
  • @Bergi, according to global warming eval should not be used at all. This is the only solution that can answer the question if firstItem is actually a dynamic variable, which I believe is true due to the question itself. Quote "access my object from a **variable** I create" – Viacheslav Jun 01 '17 at 22:22
  • No, this is [not the only solution](https://stackoverflow.com/a/6394168/1048572). – Bergi Jun 01 '17 at 22:48