Ben
Ben

Reputation: 6086

JavaScript - setting object key by name

I have a real time feed of names entering a JS function and I would like to create an object such as:

var renderObj= {
{"name": "test1", "size": 3938},
{"name": "test2", "size": 3812},
{"name": "test3", "size": 6714}
};

So renderObj is empty to start. Each time a name comes in, I need to check if it exists in the object. If it does, update the size.

Can anyone advise?

Upvotes: 0

Views: 204

Answers (3)

gotofritz
gotofritz

Reputation: 3381

I would keep a map of names side by side with the object, and a function to check that map:

var renderObj = [
      { name: "test1", size: 3938},
      { name: "test2", size: 3812},
      { name: "test3", size: 6714}
    ]
  , nameMap = {}
  ;

function notAlreadyInrenderObj( newObj ){
   //IE7 and above, use typeof ... === "undefined" if you need lower browsers
  return ( undefined === nameMap[newObj.name] );
}

then to add new objects:

if( notAlreadyInrenderObj( ojb ) ){
  nameMap[newObj.name] = renderObj.length; //in case you need to find it quickly later
  renderObj.push( ojb );
}

Upvotes: 0

ZER0
ZER0

Reputation: 25322

That's the structure you probably want:

var renderObj= {
    "test1" : 3938,
    "test2" : 3812,
    "test3" : 6714
};

Of course you can have a full object like:

var renderObj= {
    "test1" : {"size": 3938},
    "test2" : {"size": 3812},
    "test3" : {"size": 6714}
};

The key point is that the properties of your object is your "key" so you can easily check if a name is in your renderObj:

function addItem(obj, name) {
   var value = obj[name]
   if (typeof value === "number")
       obj[name] = value + 1
   else
       obj[name] = 1
}

In case of more complex object:

function addItem(obj, name) {
   var value = obj[name]

   if (value)
       value.size++ 
   else
       obj[name] = {"size": 1}
}

And then:

addItem(renderObj, "test1")
addItem(renderObj, "test4")
// etc..

Upvotes: 1

Guffa
Guffa

Reputation: 700352

You can't have unnamed items in an object. Use an array instead:

var renderObj = [
  {"name": "test1", "size": 3938},
  {"name": "test2", "size": 3812},
  {"name": "test3", "size": 6714}
];

Loop through the array to check if a name exists:

var index = -1;
for (var i = 0; i < renderObj.Length; i++) {
  if (renderObj[i].name == name) {
    index = i;
    break;
  }
}

Now check the result. I assume that you want to add an object if the name doesn't exist yet. You didn't say how you wanted the size updated, so I assumed that you wanted to add the new value to the previous:

if (index == -1) {
  renderObj.push({ name: name, size: size });
} else {
  renderObj[index].size += size;
}

Upvotes: 2

Related Questions