This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 5 years ago.
I have one array which have all the properties of values for object .
something like this.
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
console.log(ab[act[0]]);
how to access value of object using act values?
You have to split the string act[0] as your object does not contain any key named "name.first":
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
var key = act[0].split('.');
console.log(ab[key[0]][key[1]]);
try this simple
var ab = {first: 'a',
last: 'b',
age: '24'}
var ac = [];
ac.push(ab);
console.log(ac[0]);
Agree that it isn't natively supported, but you can use a little rectifier function to iterate down the passed path and get the value. This could probably be optimized, but works:
var act=["name.first","age"];
var ab={name:{first:"roli",last:"agrawal"},age:24};
function getProperty(inputObj, path) {
var pathArr = path.split('.');
var currentObjLevelOrOutput;
var i;
if (pathArr.length > 1) {
currentObjLevelOrOutput = inputObj;
for (i=0; i < pathArr.length; i++) {
currentObjLevelOrOutput = currentObjLevelOrOutput[pathArr[i]];
}
} else {
currentObjLevelOrOutput = inputObj[path];
}
return currentObjLevelOrOutput;
}
console.log(getProperty(ab,act[0]));
Related
This question already has answers here:
How to convert URL parameters to a JavaScript object? [duplicate]
(34 answers)
Closed 3 years ago.
I am trying to convert the parameters from my URL (Example 1) to a JSON Object that looks like Example 2. Unfortunately when I use JSON.stringify() it converts it to Example 3. Can anyone please point me in the right direction for splitting this? I am not sure how to get the keys out.
Example 1 - Input
food=apple,banana,peach&store=walmart&customer=John
Example 2 - Desired Output
{"food": ["apple", "banana", "peach"], "store":"walmart", "customer":"John"}
Example 3 - Current Ouput
{"food=apple,banana,peach", "store=walmart", "customer=John"}
Edits:
Forgot "" in food list
What I tried
data = "food=apple,banana,peach&store=walmart&customer=John";
data = JSON.stringify(data);
Using split, split the string appropriately and insert values in the object
var str = 'food=apple,banana,peach&store=walmart&customer=John';
var arr = str.split('&')
var obj = {};
for (let i = 0; i < arr.length; i++) {
var x = arr[i].split('=')
if (i == 0) {
obj[x[0]] = [];
x[1].split(',').forEach(function(y) {
obj[x[0]].push(y)
})
} else
obj[x[0]] = x[1]
}
console.log(obj)
This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));
This question already has answers here:
Perform .join on value in array of objects
(14 answers)
Closed 6 years ago.
I have an array of objects which are all instances of the same class like below:
class Foo {
constructor(bar){
this.bar = bar;
}
}
var myArr = [new Foo("1"), new Foo("2"), new Foo("3"), new Foo("4")];
I want to be able to join the bar property of each object in the array into a comma separated string.
Is it possible to call the .join method on the property of an object? If not is below the most efficent way to do this?
var result = "";
for (var i = 0; i < myArr.length; i++){
result += myArr[i].bar+","
}
Or is there another way?
You can use Array.prototype.map:
var result = myArr.map(function(x) { return x.bar; }).join(',');
You could use Array.prototype.reduce:
var result = myArr.reduce(function(acc, el) {
if(!acc) return el.bar;
return acc + ', ' + el.bar;
}, '');
The alternative solution using Array.reduce function:
var barValues = myArr.reduce((a,b) => (a['bar'] || a) + "," + b['bar']);
console.log(barValues); // "1,2,3,4"
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 7 years ago.
I tried to make it by myself, but I don't know if this is possible
function smth(){
var temp = [];
for(var i = arguments.length -1; i > 2; i-=1){
var temp2 = [];
temp.push(arguments[i]);
temp2.push(temp);
temp = temp2;
console.log(temp);
}
// I need to get array in this form
var something = item['collections']['0']['name'];
}
smth('collection','0','name');
edit:
Okay, maybe I haven't given you enough information.
I've got a JSON object, and I'm making a filter function, and I'd like to make it more reusable because now I have hard-coded item.collections[0].name,
and sometimes I need use item.parameters.name, and I will use it few a more times
$scope.$watch(name, function (newValue, oldValue) {
if (newValue !== oldValue) {
$scope.productsChucks = myFilter(array, function(item) {
//console.log(item['collections']['0']['name']);
if (item.collections[0].name == $scope[compareWith]) {
return item;
}
});
}
});
I think you stated your question completely wrong, IMHO it's a typical XY problem https://meta.stackexchange.com/a/66378
Anyway, based on your edit, what I think you really want is to get some nested properties of an object using a string in form "item.parameters.name".
The simplest way to do this is to use some kind of a helper library, eg. lodash:
_.get(item, 'parameters.name') // returns item.parameters.name
_.get(item, 'collections[0].name') // returns item.collections[0].name
Using that your code will look similar to this:
// path is a string given as the parameter to the filter
if (_.get(item, path) === $scope[compareWith]) {
return item;
}
Your function smth will now take only one argument:
smth('collection[0].name');
More information about lodash can be found here https://lodash.com/docs#get
If you think you don't need whole lodash you can implement this single function by yourself, take a look here https://stackoverflow.com/a/6491621/704894
If you need to access it this way:
var something = item['collections']['0']['name'];
Then it's not an array, but actually an object accessed with index notation. You can do it this way:
function smth() {
var temp = {};
var root = temp;
for (var i = 0; i < arguments.length; i++) {
temp[arguments[i]] = {};
temp = temp[arguments[i]];
}
return root;
}
console.log(JSON.stringify(smth('collection', '0', 'name'), null, 2));
This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 6 years ago.
I am using this slice of code (shown below) in an attempt to populate the object literal named Parameters inside the for loop. I need the key:value pair to be assigned in conjunction with the loops iterating i variable, as such: {key_1:chunks[1],key_2:chunks[2]}. However, my code isn't working. The 'key_'+i is not being reflected in the literal.
There's something I am missing here, obviously. Can someone tell me what it is?...Thanks.
var Parameters=[];
var len = chunks.length;
for (var i = 0; i < len; i++) {
var key='key_'+i
obj= { key : chunks[i]};
Parameters.push(obj)
}
EDIT: Use var obj = {}; obj[key] = chunks[i];
Because ECMAScript treats the key in this {key:1} as literal.
ES2015 (via Babel) Supports dynamic keys:
const Parameters=[];
const len = chunks.length;
for (let i = 0; i < len; i++) {
const key = `key_${i}`;
obj = { [key] : chunks[i]};
Parameters.push(obj);
}
(note the brackets around the key)
Or better yet:
const Parameters = chunks.map((c, i) => ({ [`key_${i}`]: c }));
same can be used for lookup: obj[key] . Do remmeber obj.key will look for key in object
var obj = {
test:1
}
var key = 'test'
obj.test = obj[key] = 1
Here obj.key will not work