I have a handful of arrays one of first names, one of last names, and one of emails. I want to create an object for each index of the arrays.
firstnames[0], lastnames[0], emails[0]
would become
{firstname: value, lastname: value, email: value}
from which I would take that object and throw it in an array. However currently I am having trouble trying to figure out how to tackle this I can't wrap my brain around it. Hoping someone can help me come up with a clean method of doing this.
You just need a loop. On each iteration of the loop get the value from each array for the current index. A simple for loop would be easiest to understand.
The following uses the array .map() method to do this. That iterates over firstnames and builds a new array containing whatever values are returned by the function passed to .map() as an argument. The advantage of this is that you don't have to manually create an output array and push objects into it, .map() does that part for you, and also it avoids creating any working variables in the current scope.
This assumes all arrays are the same length.
var firstnames = ['Annie', 'Ben', 'Chris']
var lastnames = ['Andrews', 'Brown', 'Carmichael']
var emails = ['a#a.com', 'b#b.com', 'c#c.com']
var output = firstnames.map(function(v, i) {
return {
firstname: v,
lastname: lastnames[i],
email: emails[i]
}
})
console.log(output)
Related
I cannot put strings from the associative array to another associative array. This is very weird phenomenon. This is the code and result
[Code]
p.phone_score_list.map(par => {
console.log(`par`, par);
console.log(typeof par.ipa);
phoneScoreList.push({
ipa: par.ipa,
// ipa: par.phone,
phone: par.phone,
pronuncedIpa: par.pronuncedIpa,
qualityScore: par.quality_score,
soundMostLike: par.sound_most_like,
});
});
console.log(`phoneScoreList`, phoneScoreList)
The result is below.
"ipa" and "pronuncedIpa" are "n" in the par parameter but after inputting the ipa into another associative array like the above code, it's gonna be undefined. Do you know the reason and how to handle it?
This is phone_score_list.
It's possible that you're assigning references to an object that has since been dropped from memory. I would try to create a new object like so
const newObject = { ...par };
phoneScoreList.push(newObject);
as the title describes the problem, I'm using a for loop to extract elements of an array and asign it to a JSON value, it´s something like this:
hotel={ rooms: 2, price: [ 100, 200 ], occupation: [ '1 child', '1 adult' ]
and want to push into an array of JSON
hotels = [ { rooms:1, price: 100, occupation: '1 child' },... ]
so i tried this:
var json = { rooms : 1, price:null, occupation:null }
for (let i=0 ; i < hotel.rooms ; i++){
json.price = hotel.price[i]
json.occupation = hotel.occupation[i]
this.hotels.push(json)
}
but always the array hotels has the last values of the loop and (shows repeated the last value of the iteration), tried using the try {throw i} catch(ii) {...} but doesnt work
The problem is that each element of the array this.hotels is a reference to the same json object - so when it is mutated, anywhere, all those array elements "see" the change. Since you mutate json in each loop iteration, and simply overwrite the same keys, it's inevitable that each element ends up the same.
To fix it, simply push a new "copy" of the object - which will not therefore be affected by mutations of the "master" json object. There are several ways to do this, one being object spread notation:
this.hotels.push({...json});
You could also use Object.assign({}, json) instead of the spread notation. Or keep your code as it was, but move the var json = {...} inside the loop while replacing var with let - to ensure it's a new local variable each time, rather than one global that's continually mutated. Lots of solutions, as I said.
Object are reference types, you need to create a new object each time you push to the hotels array.
There are several ways to fix this two simple ways would be to:
Use object literals in the push method this.hotel.push({ rooms: 1, price: hotel.price[i], occupation: hotel.occupation[i]})
--OR--
Move the variable declaration into your loop var json = { rooms : 1, price:null, occupation:null }
I'm calling an external service and I get the returned domain object like this:
var domainObject = responseObject.json();
This converts the response object into a js object. I can then easily access a property on this object like this
var users = domainObject.Users
Users is a collection of key/value pairs like this:
1: "Bob Smith"
2: "Jane Doe"
3: "Bill Jones"
But CDT shows users as Object type and users[0] returns undefined. So how can I get a handle to the first item in the collection? I'm assuming that some type of type cast is needed but not sure how I should go about doing this
UPDATE
Here is one way I could access the values:
//get first user key
Object.keys(responseObject.json().Users)[0]
//get first user value
Object.values(responseObject.json().Users)[0]
But I need to databind through ng2 so I was hoping for a simpler way like this:
<div>
<div *ngFor="let user of users">
User Name: {{user.value}}
<br>
</div>
</div>
Maybe I should just create a conversion function in my ng2 component which converts the object into what I need before setting the databinding variable?
UPDATED ANSWER
So after scouring through a few docs I found the "newish" Object.entries() javascript function. You can read about it here. Pretty cool.
Anyways, give this a try. I am ashamed to say that I don't have time to test it, but it should get you going in the right direction.
usersArray = []
// Turn Users object into array of [key, value] sub arrays.
userPairs = Object.entries(users);
// Add the users back into an array in the original order.
for (i=0; i < userPairs; i++) {
usersArray.push(_.find(userPairs, function(userPair) { return userPair[0] == i }))
}
ORIGINAL ANSWER
I would use either underscore.js or lodash to do this. Both are super helpful libraries in terms of dealing with data structures and keeping code to a minimum. I would personally use the _.values function in lodash. Read more about it here.. Then you could use users[0] to retrieve the first item.
The only caveat to this is that lodash doesn't guarantee the iteration sequence will be the same as it is when the object is passed in.
users = _.values(users);
console.log(users[0]);
How about this:
let user= this.users.find(() => true)
This should return the "first" one.
If your initial object is just a plain object, how do you know it is sorted. Property members are not sorted, ie: looping order is nor guaranteed. I´d extract the user names into an array and the sort that array by the second word. This should work (as long as surnames are the second word, and only single spaces are used as separators).
var l=[];
for(var x in users) {
push.l(users[x]);
}
var l1=l.sort ( (a,b) => return a.split(" ")[1]<b.split(" ")[1]);
I've spent the last couple hours going through some very similar answers to the above question but after a few implementations of loops and reduce I still have not gotten the solution I need.
I am getting an array of objects via service calls. I am pushing those controller array objects to another array because I need a single array to load data into a multi select. I.E.
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.areaOptions.push(controller.cities);
});
StatesService.getAreaStates().then(function(response) {
controller.states = response.data.rows;
controller.areaOptions.push(controller.states);
});
controller.areaOptions = [];
This is an example of how I expect and need my array object to look.
With no modification this is how my array looks with those array objects pushed in.
How do I get the above data structure like the 1st image, an array of objects? I tried a solution with reduce()
var newCities = controller.cities.reduce(function(city){
return controller.city;
}, {});
controller.areaOptions.push(newCities);
but it wasnt what I was looking for because it returned a single object with all city property and all its values. I need each object to contain city and its value.
EDIT
I figured out the solution! Thanks to Lex.
I looped over each object in the array in each service and pushed the property.
Thanks to all for steering me in the right direction to figure this out, even the person that downvoted me :)
StatesService.getAreaCities().then(function(response) {
controller.cities = response.data.rows;
controller.cities.forEach(function(city){
controller.areaOptions.push(city);
});
});
Looks like response.data.rows is an array. So when you push response.data.rows into controller.areaOptions you are adding the rows array as an array element. (Basically making it a 2-dimensional array)
You should use Array.prototype.concat
Can i create javaScript object with just value (without mentioning of property) and an array of objects inside it?
Like below:
Car = {'12345', [{type:"Fiat", model:"500", color:"white"}]}
I tried like this.
It works but i want to get rid of Id and Values from output
var Cars = {Id: '12345', Values:[{type:"Fiat", model:"500", color:"white"}}]}
Objects are key-value stores, so what you want to achieve is not possible.
But begs the question, why do you want to make the data an object?
You can still work very effectively with arrays:
Car = ['12345', [{type:"Fiat", model:"500", color:"white"}]]