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"
Related
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I am passing a dot separated string into function
console.log( namespace('a.b.c.d.e'))
and expect get next result
//result => "{"a":{"b":{"c":{"d":{"e":{}}}}}}"
my try (I don't know how to do it recursively)
const namespace = (string)=> {
return string.split('.').reduce((acc,el)=>{
acc[el] = {}
},{})
}
const input = "a.b.c.d.e"
const output = input.split('.').reverse().reduce((acc,el)=>{
return {[el]: acc}
},{})
console.log(output)
How about the below iteration approach :-
function namespace(input){
let result = {};
let temp = result;
const inputArr = input.split(".");
inputArr.forEach((ele)=>{
temp[ele] = {};
temp = temp[ele];
})
return result;
}
console.log( namespace('a.b.c.d.e'))
This question already has answers here:
Push Object in Array [duplicate]
(2 answers)
Closed 4 years ago.
const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";
const result = [];
const temp = { reqId: req, batch: null };
for (var x = 0; x < maxObj.length; x++) {
temp.batch = maxObj[x];
result.push(temp);
}
console.log(JSON.stringify(result));
In this code I'm trying to iterate through an an array of objects and assigning each object to the property of a temporary template object that I then push to the results array. My expected output is something like this:
[{"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
{"reqId":"4976809","batch":{"BTCH#BD":57887,"BTYPEBD":"OCO"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]
But my actual output is like this:
[{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}},
{"reqId":"4976809","batch":{"BTCH#BD":57890,"BTYPEBD":"OTH"}}]
How do I fix this so I get the expected output above?
You use the same object for pushing. You get same objects inside of the array.
You could use a new object with wanted property to prevent to store the same object reference.
const maxObj = [{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57887,"BTYPEBD":"OCO"},
{"BTCH#BD":57890,"BTYPEBD":"OTH"}]
const req = "4976809";
const result = [];
for (var x = 0; x < maxObj.length; x++) {
result.push({ reqId: req, batch: maxObj[x] });
}
console.log(JSON.stringify(result));
This question already has answers here:
How to create an array containing 1...N
(77 answers)
Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]
(1 answer)
Closed 4 years ago.
I want to create a function that takes input from user and returns an array with all the numbers from 1 to the passed number as an argument. Example: createArray(10) should return [1,2,3,4,5,6,7,8,9,10]. I came up with this solution:
function createArray(input) {
var value = 0;
var array = [];
for (i=0;i<input;i++) {
value++;
array.push(value)
console.log(array)
}
}
createArray(12);
What is the correct and better way of doing it?
I would prefer to use Array.from:
const createArray = length => Array.from(
{ length },
// Mapper function: i is the current index in the length being iterated over:
(_, i) => i + 1
)
console.log(JSON.stringify(createArray(10)));
console.log(JSON.stringify(createArray(5)));
There is no need for the extra variable just do this:
function createArray(input) {
var array = [];
for (i = 0; i <= input; i++) {
array.push(i);
}
return array;
}
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]));
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('')));