How to initialize an empty array of object with a predefined array? - reactjs

I am facing lot of issue to initialize an array of object with a predefined array. I am not being able to copy that array to my new array of objects. If anyone knows it then let me know.
admins is basically an array which contains string items like ["hello","hii","sup",....]
var admins = ["hello","hii","sup"];
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i].name = admins[i];
}
console.log(obj);
"TypeError: Cannot set property 'name' of undefined"

Use a map:
var newArray = admins.map((admin) => ({ name: admin }));

IMHO: use spread operator:
const admins = ["John", "Doe", "Duck"];
const obj = [...admins].map(
(admin) => ({ name: admin })
);
console.log(obj);

Try out this
var obj = [];
for (var i = 0; i < admins.length; i++) {
let temp = {};
temp["name"] = admins[i];
obj.push(temp);
}
console.log(obj);

You need to define the obj[i] to empty object (obj[i] = {}).
you are trying to access name property of undefined(obj[i] is undefined in your code).
var obj = [];
for(var i=0; i<admins.length; i++)
{
obj[i] = {
name: admins[i]
}
}
console.log(obj);

Related

Mutating the object in the setState [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

Creating and pushing elements in an new array depends on conditions

My Data Array
data:[
0:{
id:1 ,.....
competetion:[
0:{
id: 1....,
match:[
0:{id: 1 ......},
1:{same}
.
.
]
1:{same}]},
2:{same}
.
.
]
},
1:{same},
2:{same}
.
.
.
]
For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...
My Code: Here i am looping it:
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
this.sportarr.push({ // I declared a new array where i want to push the element
id: i,
value: false
});
}
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map
const arrlength = data.length;
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = data[i].competetion.map( (val, index) => {
#write your own logic to produce the required outcome
return {
id: index,
value: false
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = response.data[i].competetion.map((val, index) => {
let match = [];
match = val.match.map((value, indx) => {
return {
id: indx,
value: false
};
});
return {
id: index,
value: false,
match
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
}
Now i am getting what i wanted
i am not sure if you are trying to create an array for each nasted array (competetion and match) or not, but here you go
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const competetionList = // Array of competetions
[].concat.apply([], this.sportsSidebar.map(item => item.competetion));
const matchList = // Array of matchs
[].concat.apply([], competetionList .map(item => item.match));
}

how to use var as key of object into react project [duplicate]

I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key" instead of the value of the variable key. Is there any way to set the value of the key from a variable?
Fiddle for better explanation:
http://jsfiddle.net/Fr6eY/3/
You need to make the object first, then use [] to set it.
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2021:
Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.
const yourKeyVariable = "happyCount";
const someValueArray= [...];
const obj = {
[yourKeyVariable]: someValueArray,
}
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also
supports computed property names. That allows you to put an expression
in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
Use this.
var key = 'a'
var val = 'b'
console.log({[key]:val})
//a:'b'
In ES6 We can write objects like this
const key= "Name";
const values = "RJK"
const obj = {
[key]: values,
}
In TypeScript, it should look something like this
let title ="Current User";
type User = {
[key:string | number | symbol]: any
};
let myVar: User = {};
myVar[ title ] = "App Developer";
console.log(myVar)// Prints: { Current User:"App Developer"}
let key = "name";
let name= "john";
const obj ={
id:01
}
obj[key] = name;
console.log(obj); // output will {id:01,name:"john}
Use square brackets shown it will set as key
The Reality
The problem in JS is simply that:
{ x: 2 }
is THE SAME as:
{ "x": 2 }
(even if you have x a variable defined!)
Solution
Add square brackets [] around the identifier of the key:
var key = "happyCount";
myArray.push( { [key] : someValueArray } );
(Nowadays the keyword var is not much used, so please use instead const or let)
tldr;

Insert data into array with specific index in Angular 4

Why that is not working in TypeScript?
Example:
views: any[] = [360001232825, 360001232845, 360001217389];
MyArray:any[];
for (var i = 0; i < this.views.length; i++) {
this.subscription = this.dataService.getMyData(this.views[i]).subscribe(data => {
this.myArray[this.views[i]]=data;
});
}
When I use .push data is inserted into my array but I want to use a specific index.
If you want to insert an Item use splice. But obviously you want to use a Map or an object.
let ar = ["one", "two", "four", "five"];
console.log("Before:\n" + ar);
ar.splice(2, 0, "three");
console.log("After:\n" + ar);
Maybe this will help:
let namedIndexes = [1564789, 234895, 249846];
let map = {};
let data = "this is your data arg";
namedIndexes.forEach((v, i, ar) => {
map[v] = data + " data at " + v;
});
console.log(map);
'map' is like your this.myArray, 'data' is your parameter and 'namedIndexes' is your view array. I hope the code explains itself.

how to get index position of an array item in controller passing a value in angularjs

I have an array with list of values.
[Object { id="5", country="UAE"}, Object { id="4", country="India"}]
I want to get the index of array item based on the value present in the id. How can I get the index position of an array item with value of id = 4 in angularJS Controller?
The angularjs way (using $filter) would be something like this
app.controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {
//array
var items = [{ id: "5", country: "UAE" }, { id: "4", country: "India" }];
//search value
var id2Search = "4";
//filter the array
var foundItem = $filter('filter')(items, { id: id2Search }, true)[0];
//get the index
var index = items.indexOf(foundItem );
}]);
this is not angularjs specific problem but normal javascript.
just loop and return the index
var list = [{ id="5", country="UAE"}, { id="4", country="India"}];
for (var i = 0; i < list.length ; i++) {
if (list[i][id] === 4) {
return i;
}
}
you can then make it generic by making it function on array which accepts the value and property name
Array.prototype.getIndexOfObject = function(prop, value){
for (var i = 0; i < this.length ; i++) {
if (this[i][prop] === value) {
return i;
}
}
}
You can use the map() function to iterate over each object in your array and inspect any desired property. For example if you have an array of objects
$scope.items =
[
{'id':'1','name':'item1'},
{'id':'2','name':'item2'}
];
to get the index of the second object in the array use
var index = $scope.items.map(function (item) {
return item.id;
}).indexOf(2);
returns the index of the object containing the value of 2 in the id property.
Pass the id that you want to remove from the array to the given function from the controller (function can be in the same controller but prefer to keep it in a service).
function removeInfo(id) {
let item = Object .filter(function(item) {
return Object.id === id;
})[0];
let index = Object.indexOf(item);
}

Resources