I'm looping through an array and for each element 1) checking if it's a property in my object, 2) and if not, adding it to obj as prop with the val of it's index. Code is here in full as i'm not sure which part contains the error.
var repeat = function(arr) {
for(let i=0; i<arr.length; i++){
const obj = {};
if (obj.hasOwnProperty(arr[i])) {
return arr[i]
} else {
obj.arr[i] = i;
}
}
};
I'm getting the error "Cannot set property of '0' to undefined".
I did search similar questions and errors but didn't find an answer within the context of objects. Would appreciate insight as to this specific error and/or where my code is going wrong.
You trying to check the properties in a empty object. const obj = {}; You have to pass the object in to the function as well. When adding the property to a object it should be like this obj["New Property"] = value. We can't add new values using .(dot) as we access values from objects.
var repeat = function(arr,obj) {
var pObj = {}
for(let i=0; i<arr.length; i++){
if(!obj.hasOwnProperty(arr[i])){
pObj[arr[i]] = i
}
}
const a = {...obj, ...pObj};
return a;
};
var myarr= ["a","b","c","d"];
var myObj = {a:"Property A",b:"Property B"};
this.repeat(myarr,myObj)
Related
I'm trying to create a new javascript object that'll have new key names based on another object. I'm almost there, but my code fails at the line // fails here with Uncaught TypeError: Cannot set property 'name' of undefined . Any idea how to get this right? Also, is there a more efficient way to build a new object in this case? I need it work on older IE browsers, hence this approach.
originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};
objCodes = {"name":101,"age":102,"state":103,"country":104};
// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
newObj = {};
for (var i in originalObj) {
if (objCodes.hasOwnProperty(i)) {
// console.log(i, originalObj[i]);
console.log(objCodes[i],originalObj[i])
newObj.objCodes[i] = originalObj[i] // fails here
}
}
console.log(newObj);
Just change the line like in the snippet below
originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};
objCodes = {"name":101,"age":102,"state":103,"country":104};
// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
newObj = {};
for (var i in originalObj) {
if (objCodes.hasOwnProperty(i)) {
// console.log(i, originalObj[i]);
console.log(objCodes[i],originalObj[i])
newObj[objCodes[i]] = originalObj[i] // fails here
}
}
console.log(newObj);
originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};
objCodes = {"name":101,"age":102,"state":103,"country":104};
// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
newObj = {};
for (var i in originalObj) {
if (objCodes.hasOwnProperty(i)) {
// console.log(i, originalObj[i]);
console.log(objCodes[i],originalObj[i])
newObj[objCodes[i]] = originalObj[i] // fails here
}
}
console.log(newObj);
Change the dotted notation to bracket notation. Reason for this is JavaScript allows only valid names with dotted notation which cannot start with numeric value.And In your case the keys are set to be 101,102...and so on, which are invalid.
Edit : Dynamic property names can be used only through bracket notations, such as in your case where the property name is set using a variable.
You can get the keys, iterate them and copy the items like this:
originalObj = {"name":"John","age":30,"state":"CA","country":"USA"};
objCodes = {"name":101,"age":102,"state":103,"country":104};
// newObj = {101:"John", 102:30,103:"CA",104:"USA"};
newObj = {};
Object.keys(objCodes).forEach(i => newObj[objCodes[i]] = originalObj[i]);
I am basically trying to get this problem to work and have isolated the issue to line 21. I think the way I'm trying to access the object key is wrong. I am simply trying to say: if the object key in the new object exists in the original array, push the new value from the new object into the new array.
Edit to add code block
function valueReplace(array, obj) {
var replaced = [];
for (var i = 0; i < array.length; i += 1) {
var value = obj[array[i]];
if (array.indexOf(obj.i) !== -1) {
replaced.push(value);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
You have a mixed up error report, but at the actual code, you try to access the object with the property i, obj.i, which not exists. Read more about property accessor.
For getting the wanted result, you might use the in operator for checking if a property in an object exists.
if (array[i] in obj) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
It looks like one of the issues you are having is trying to access a dynamic property with dot notation, which JS generally doesn't like. I reversed your logical if because IMO it makes more sense to see if the object has a property than get a property and then get the index of the array, but you could reverse it back to using index of by array.indexOf(obj[i]) !== -1
function valueReplace(array, obj) {
let replaced = [];
for (let i = 0, len = array.length; i < len; i++) {
if (obj.hasOwnProperty(array[i])) {
replaced.push(obj[array[i]]);
} else {
replaced.push(array[i]);
}
}
return replaced;
}
Because I generally like simplifying things here is this functionality rewritten in ES6 compatible code, using array.prototype.map. Don't use it for your homework, but if you want you can work it backwards into a standard function ;).
const valueReplace = (array, obj) => array.map(val => (obj.hasOwnProperty(val)) ? obj[val] : val);
I'm trying to achieve this structure (a JSON Object with an array inside):
var data = {
page : 'hello',
rows: [
{
column: 'two'
}
]
}
But i'm failing miserable, trying various methods, this is my work in progress code:
var data = new Array();
data['settings'] = [];
var i = 0;
var inputName, value;
for (i; i < inputs.length; i++){
inputName = $(inputs[i]).attr('name');
value = $(inputs[i]).val();
data['settings'][inputName] = value;
}
data['page_id'] = page_id;
So i know the variable names are not the same as the desired example but you get the general gist! At the moment, its just making data an empty array. But i need to make it a JSON object with the idea to send it to a server.
What you've quoted is a JavaScript object with a JavaScript array in it, no JSON* in sight.
To create it, I don't think you want an array at all, just an object with a nested object:
var data = {
settings: {},
page_id: page_id
};
var i, input;
for (i = 0; i < inputs.length; i++){
input = $(inputs[i]);
data.settings[input.attr('name')] = input.val();
}
That works because JavaScript objects are maps of name/value pairs. You can refer to a property of an object using dotted notation and a literal property name:
x = obj.foo;
...or using bracketed notation and a string name:
x = obj["foo"];
In the latter case, you can use any expression you like for the string, so for instance:
x = obj["f" + "o" + "o"];
JavaScript also has literal object initializers, which you can use to create an object with properties already on it:
obj = {foo: "bar"};
That creates an object with a property called foo with the value "bar" and assigns the object to the obj variable.
So looking again at the code block above:
We create an object with the properties settings and page_id. settings is initialized with a blank object; page_id is initialized with the value of the page_id variable.
Then we loop through your inputs and add properties to settings using the name of each input, setting the value of the property to be the value of the input.
So let's assume we have
<input name="oneField" value="bar">
<input name="anotherField" value="bang">
<input name="yetAnotherField" value="cool">
...and let's assume page_id is 3.
We'll end up with this structure in the object referenced by the data variable:
{
settings: {
oneField: "bar",
anotherField: "bang",
yetAnotherField: "cool"
},
page_id: page_id
}
* JSON is a textual notation. When you're writing things like var data = { ... }; in code, you're just using JavaScript. JSON is a subset of JavaScript literal syntax that's designed to be easy to parse, so for instance it's handy for storing arbitrary complex data in data stores, or for retrieving data from a server. You retrieve the string, which contains the data, and then parse that string to build up an object structure in memory.
var data = {};
data['settings'] = {};
var i = 0;
var inputName, value;
for (i; i < inputs.length; i++){
inputName = $(inputs[i]).attr('name');
value = $(inputs[i]).val();
data['settings'][inputName] = value;
}
data['page_id'] = page_id;
This will give you such result like below:
{
page_id: 12345,
setting: { foo: 'one', bar: 'two'}
}
Both [] and new Array() are used to initialize an array; what you're after (as you're trying to map keys to values), are objects; which are initialized using either {} or new Object().
var data = {};
data['settings'] = {};
var i = 0;
var inputName, value;
for (i; i < inputs.length; i++){
inputName = $(inputs[i]).attr('name');
value = $(inputs[i]).val();
data['settings'][inputName] = value;
}
data['page_id'] = page_id;
To help you with your syntax, square bracket notation is only needed if the member you're looking up is a variable, or if the key contains reserved words or special characters (spaces etc). Otherwise, you can use dot notation;
var data = {};
data.settings = {};
var i = 0;
var inputName, value;
for (i; i < inputs.length; i++){
inputName = $(inputs[i]).attr('name');
value = $(inputs[i]).val();
data.settings[inputName] = value;
}
data.page_id = page_id;
When using object literal syntax ({}) to construct an object, you are allowed to define members on the object as well. It's also more common to declare your looping variable within the for loop rather than outside.
var data = {
settings: {}
};
var inputName, value;
for (var i=0; i < inputs.length; i++){
inputName = $(inputs[i]).attr('name');
value = $(inputs[i]).val();
data.settings[inputName] = value;
}
data.page_id = page_id;
I have a JavaScript object that I'd like to add some properties to, but I don't know what the names of the properties are until runtime.
Can I do this without using eval? If so, how?
var get_params = new Object();
var params = {'name':'john', 'age':'23'}; //actually not known until runtime
for (var i=0, len=params.length; i<len; ++i ){
get_params.p[0] = p[1]; //How can I set p[0] as the object property?
}
}
Since your code example has a malformed array, I will include 2 variations.
Variation 1 (params is an actual object and not an array):
var get_params = {}; // prefer literal over Object constructors.
var params = {'name':'john', 'age':'23'}; // #runtime (as object literal)
for (var key in params){
if(params.hasOwnProperty(key)) { // so we dont copy native props
get_params[key] = params[key];
}
}
Variation 2 (param is an array containing objects):
var get_params = {}; // prefer literal over Object constructors.
var params = [{'name':'john'},{'age':'23'}]; // #runtime (as array literal)
for(var i=0,param;param=params[i];i++) {
for (var key in param){
if(param.hasOwnProperty(key)) {
get_params[key] = param[key];
}
}
}
Enjoy.
You can access objects via object['someKey'] as well.
var get_params = {};
var params = [{'name':'john'}, {'age':'23'}];
for (var i=0,len=params.length; i<len; ++i){
for (var p in params[i]) {
if(params[i].hasOwnProperty(p)) {
get_params[p] = params[i][p];
}
}
}
Ok, that's my third version. I think it will do what I understand you to desire. Kind of convoluted however, and there are probably better formats for your dynamic array. If I understand what you want to do correctly, this should work. Basically, it creates the following object:
get_params = {
name: "john",
age: "23"
}
I am trying to remove an element from a Javascript associtive array using the value to find it, but I am having trouble. I have tried splice and JQuery's grep method and neither have worked for me. This is what I currently have.
var array_path = new Array();
function bulk_upload(){
var temp_array = new Object();
for (var i = 1; i<8; i++){
temp_array[i] = $('#path' + i).val();
if(temp_array[i]!='' && temp_array[i]!=null){
array_path['path' + i] = $('#path' + i).val();
}
}
process_txt();
}
function process_txt(){
//alert(array_path.indexOf(full_path)); //returns nothing
var removed_element = array_path.splice(getKey(array_path), 1);
//array_path = $.grep(array_path, function(val) { return val != full_path; });
alert(removed_element);//return nothing, just blank alert box
}
function getKey(data) {
for (var prop in data)
return prop;
}
The way to do this is to use the delete operator.
delete array_path[getKey(array_path)]
Some Background Information
In JavaScript, almost everything descends from Object.prototype. JavaScript, being an open and dynamic language allows you to create/modify properties of objects by simple assignment. This is very similar to what an associative array -- a structure that contains keyed values.
Under the hood an array is just an object that descends from Array.prototype with numeric keys and a special property called length. The length property just returns one greater than the highest numeric property. In essence, an Array is an object with different semantics.
If you're wanting an associative array then Array is not the object you want to descend from. You would want to descend directly from Object. There are two ways to do that, you could either use the new operator or an empty object literal. The syntax for both is below:
var o = new Object();
var o = {};
The second is preferred since it's a little bit more concise.
I wrote a blog post about this a while back, have a look if you want a little bit more info.
There is no such thing in JavaScript as an "associative array" per se. The data structure which corresponds to this concept is simply a JavaScript Object.
Of course, a JavaScript Array (like essentially everything in JavaScript) is an Object, but one with additional capabilities. So you can use an Array as a key-value map, but it's really not the correct structure for that.
To remove a key from an Object, you just do something like this:
var myObj = {};
var myKey = "blah";
myObj[myKey] = 1234; // Adds or updates value for "blah" to 1234.
delete myObj[myKey]; // Removes key-value pair for "blah".
Have you tried delete hash.someKey; ?
You can give your object a remove method, or use apply or call to use another object's remove method, if defined.
function myObj(members){
for(var p in members) this[p]= members[p];
}
myObj.prototype.remove= function(val){
for(var p in this){
if(this[p]=== val) delete this[p];
}
return this;
}
myObj.prototype.toString= function(){
var A= [];;
for(var p in this){
if(this.hasOwnProperty(p)){
A.push(p+':'+this[p])
}
}
return '{'+A.join(', ')+'}';
}
var O= new myObj({a: 1, b: 10, c: 100});
alert(O)
O.remove(10);
alert(O)
I'm not psychic, so I can only guess that you wanted to accomplish something like this:
var paths = [];
function getPaths() {
for(var i = 1; i < 8; ++i) {
var value = $('#path' + i).val();
if(value) paths.push(value);
}
}
function process() {
var firstPath = paths.shift();
// do stuff
}
getPaths();
if(paths.length) process();