0

Here's the situation: I want to process item-objects with a function. The item-objects have a property "name", but that's only a short version of the fullname.

I also got a list-object, which has shortnames of items as properties, and fullnames as values of these properties. Here are the objects, like you would try in a node-console:

var itemobj = {"name":"a","amount":"10","price":"5"};
var listobj = {"a":"adler","b":"blume","c":"chicken"};

Unfortunately, not all item-objects have a property like their own name-properties value in the list-object. For those I want to set the default-fullname "noname". Here is the code I thought should work:

function fullname(io){
  if (listobj.hasOwnProperty(io.name)){
    var shortn = io.name;
    var fulln = listobj.shortn;
    io.fullname = fulln;
  } else {
    io.fullname = "noname"
  }
};

But running the following I get the output shown:

fullname(itemobj);
console.log(itemobj);
{ name: 'a', amount: '10', price: '5', fullname: undefined }

I would expect:

{ name: 'a', amount: '10', price: '5', fullname: 'adler' }

What do I do wrong?

3 Answers3

0

Given the fact that listobj.hasOwnProperty(io.name) might return true (so listobj actually has that property), you just have to access it, since it is safe. No need to play around with other variables.

Your mistake is that shortn will have the value adler, but listobj.shortnactually access the shortn named field from listobj, which is nonexistent. You want to use its value, so you need to use square brackets.

Check the fiddle below.

var itemobj = {"name":"a","amount":"10","price":"5"};
var listobj = {"a":"adler","b":"blume","c":"chicken"};

function fullname(io) {
  console.log("Searching: " + io.name);
  if (listobj.hasOwnProperty(io.name)) {
    io.fullname = listobj[io.name];
  } else {
    io.fullname = "noname"
  }
};

fullname(itemobj);
console.log(itemobj);
Adrian Pop
  • 1,879
  • 5
  • 28
  • 40
0

listobj.shortn should be listobj[shortn]. You want to use the value of shortn as the property key.

var itemobj = {"name":"a","amount":"10","price":"5"};
var listobj = {"a":"adler","b":"blume","c":"chicken"};

function fullname(io){
  if (listobj.hasOwnProperty(io.name)){
    var shortn = io.name;
    var fulln = listobj[shortn];
    io.fullname = fulln;
  } else {
    io.fullname = "noname"
  }
};

fullname(itemobj);
console.log(itemobj);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

Since io.name returns a string, the way you access properties of an object in JavaScript by string is via bracket notation. Your program should work is you change var fulln = listobj.shortn; to var fulln = listobj[shorn].

Syed Aslam
  • 8,707
  • 5
  • 40
  • 54