This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I want to parse a string to an object object selector like so :
var test = 'object.prop1.prop2';
into
object['prop1']['prop2'];
The problem is i don't know how many properties the string could have.
What is the best way to to parse a string accross, idealy without something like json parse/ eval?
There is a package for that :
https://www.npmjs.com/package/object-path
Juhana's link is excellent, but also a bit more of a complex problem than the one you have here. Here is my take (https://jsfiddle.net/gm32f6fp/3/):
var object = {
prop1: {
prop2: {
foo: 1
}
}
};
function get(object, key) {
var keys = key.split('.');
for (var i = 0; i < keys.length; i++) {
if (!object.hasOwnProperty(keys[i])) {
return null;
}
object = object[keys[i]];
}
return object;
}
console.log(get(object, 'prop1.prop2'));
console.log(get(object, 'prop1.prop3'));
The idea is to take the string of keys, split it based on the dot. Then you have an arbitrarily large array of keys, so we take each key, one by one, and dive into the object. (If we end up at a dead end, we bail out.)
Related
This question already has answers here:
Object comparison in JavaScript [duplicate]
(10 answers)
How to determine equality for two JavaScript objects?
(82 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 3 years ago.
I have this data
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
I want to check if my new data is already exists in that array. I'm trying to use includes()
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
Then i try another way
function inArrayCheck(val) {
if (Object.values(selectedValue).indexOf(val) > -1) {
console.log(val);
}
}
both of them returning false when i input Data A
Objects will not be equal unless they have the same reference, even when they have the same key/value pairs. You can do the comparison after converting the objects to string using JSON.stringify with limited capability, like the order of elements in the object and the case of strings matters:
var selectedValue = [];
selectedValue.push({0:'Data A'});
selectedValue.push({1:'Data B'});
function inArrayCheck(val) {
return selectedValue.some(obj => JSON.stringify(obj) === JSON.stringify(val))
}
console.log(inArrayCheck({0:'Data A'}))
You are trying to find a value from an object which is inside an array. You can try like so:
var selectedValue = []; // this is an array
selectedValue.push({0:'Data A'}); // here you push an object to the array
selectedValue.push({1:'Data B'}); // to find the value later you need to find it inside the object!
// above three lines can also be written like so and are the same
// var selectedvalue1 = [{0:'Data A'}, {1:'Data B'}];
function inArrayCheck(val) {
selectedValue.forEach(function(element){
if (Object.values(element).indexOf(val) > -1) {
console.log('found value: ' + val);
}
});
}
inArrayCheck('Data A');
if you want to use includes you need to have an array like so:
var selectedValue = [];
selectedValue.push('Data A');
selectedValue.push('Data B');
// above three lines can also be written like so and are the same
// var selectedvalue1 = ['Data A', 'Data B'];
function inArrayCheck(val) {
console.log(selectedValue.includes(val));
}
inArrayCheck('Data A')
You forgot to go trough each value. You can also use find() function, to check if array have a value which sutisfy your condition.
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 4 years ago.
I know this is probably easier than my brain is making it, but for some reason, I can't get this right:
I have an array looks like this:
["engine", "engine.car", "engine.car.driver",
"engine.car.passenger", "wheels", "wheels.tires"]
I want to transform above array into this object:
{
engine : {
car : {
driver : undefined,
passenger: undefined
}
},
wheels : {
tires: undefined
}
}
I'm using node 8.10.0.
This is pretty straightforward with JavaScript and the eval functionality. Here is a quick example.
var arr = ["engine", "engine.car", "engine.car.driver", "engine.car.passenger", "wheels", "wheels.tires"];
obj = {};
for(var i = 0; i < arr.length; i++)
eval("obj." + arr[i] + " = {}");
console.log(obj);
Edit
Eval is not evil, most implementations of it are but this is a perfectly valid use of it as outlined in the comments below. If you have an issue with this answer please use the comments to let me know why so I can either update the answer or OP can get the help they need.
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
Not sure if my title describes what I want to do correctly. Basically, I want a function that extracts properties from objects containing objects. I am going to need to loop through various arrays containing many objects of the same class and extract specific values.
myarray1[
0:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
}
1:
object2 = { same as object1 but with other property values }
];
myarray2[
0: { different type of object with a different set of nested properties that the function can extract }
1: { idem }
];
function extractProperty(objectArray, property) {
//How do I write this code?
propertyvalue = objectArray.property;
return propertyvalue;
}
extractProperty(myarray1[0], object.objectProp3) = "Seeya"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop1) = "Hello"
extractProperty(myarray1[0], object.objectProp1.objectProp1Prop3.objectProp1Prop3Prop1) = "Come here"
In the final code the function needs to be able to loop through all the array keys and create an array list containing the chosen property from every object in the original array, but that I can manage. It's the sending of the specific property that needs to be extracted from the objects in the array into the function that I have no idea how to do.
Is there a generalised way to send a "path" of properties into a function and then use it there? How?
Thanks for your help!
Looks like an assignment to me. So I won't give you the code but will explain the approach.
First you need to pass the property names as a string
In your function you need to split the string based on the delimiter, like .
Keep a reference of current object
Then iterate on all the property names that you got from #2
Fetch current property name from current object and replace current object with the returned value.
return current object at the end.
Note: you need to add some validations in between. I've skipped those for you to explore ;)
You could try recursion:
object1 = {
objectProp1: {
objectProp1Prop1:"Hello",
objectProp1Prop2:"Goodbye",
objectProp1Prop3:{
objectProp1Prop3Prop1: "Come here",
objectProp1Prop3Prop2: "Go away"
},
},
objectProp2: "Yo",
objectProp3: "Seeya",
};
object2 = {
objectProp1: 'test1',
objectProp2: 'test2'
}
var myArray = [object1, object2];
function getProp(objArray, prop) {
for(var key in objArray) {
if (key == prop)
return objArray[key];
if (typeof objArray[key] == 'object')
return getProp(objArray[key], prop);
}
}
//test
document.getElementsByTagName('h1')[0].innerHTML = getProp(myArray[0],'objectProp1Prop3Prop1');
I added a Fiddle for you to try it: https://jsfiddle.net/afabbro/vrVAP/
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 8 years ago.
I have a a function that takes a string like "obj.key.subkey.subsubkey":
function(obj, key) {
return eval('obj.'+ key);
}
What would be a safe alternative to eval in this case or is eval fine? new Function won't work in this case AFAIK. Maybe split and loop then?
I'm not sure you really need a function here. If you have the object and the key just use the key to return the property on the object.
obj[key]
If you must handle multiple keys:
function get(obj, key) {
var keys = key.split(".");
var tmp = obj;
for (var x = 0; x < keys.length; x++){
tmp = tmp[keys[x]];
}
return tmp;
}
Working Example: http://jsfiddle.net/H55ka/
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Javascript - array.contains(obj)
Best way to find an item in a JavaScript Array ?
I want to check, for example, for the word "the" in a list or map. Is there is any kind of built in function for this?
In javascript you have Arrays (lists) and Objects (maps).
The literal versions of them look like this:
var mylist = [1,2,3]; // array
var mymap = { car: 'porche', hp: 300, seats: 2 }; // object
if you which to figure out if a value exists in an array, just loop over it:
for(var i=0,len=mylist.length;i<len;i++) {
if(mylist[i] == 2) {
//2 exists
break;
}
}
if you which to figure out if a map has a certain key or if it has a key with a certain value, all you have to do is access it like so:
if(mymap.seats !== undefined) {
//the key 'seats' exists in the object
}
if(mymap.seats == 2) {
//the key 'seats' exists in the object and has the value 2
}
Array.indexOf(element) returns -1 if element is not found, otherwise returns its index