I have an array consisting of a list of words, and a wordcount and ID for each word. Sort of like:
var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]]
Now I want to create an object for each word with the word as the name and the count and ID as values. So it would look like this:
var word1 = {count: 3, id: 'id1'}
How do I achieve this?
I tried doing it using a for-loop as shown below, but it doesn't work. How could I set the name of each object from the values in the array?
for (var y=0; y < array[0].length; y++) {
var array[0][y] = {count: array[1][y], id: array[2][y]};
}
Instead of having individual objects you could add the words in one dict object like this:
var words = {};
for (var y=0; y < array[0].length; y++) {
words[array[0][y]] = {count: array[1][y], id: array[2][y]};
}
And, you can access word1 as following:
words['word1'] // {count: 1, id: id1}
// if the word1 doesn't contain spaces, you could also use
words.word1 // {count: 1, id: id1}
If you know that the array [0] are the ordered keys, and array[1] are the count and array[2] are the ids then:
var array = [[word1, word2, word3],[3,5,7],[id1,id2,id3]];
var orderedKeysArray = array[0];
var orderedCountArray = array[1];
var orderedIdArray = array[2];
//maybe add some code here to check the arrays are the same length?
var object = {};
//add the keys to the object
for(var i = 0; i < orderedKeysArray.length; i++) {
object[orderedKeys[i]] = {
count: orderedCountArray[i],
id: orderedIdArray[i]
};
}
Then you can refer to the object for the vars like so:
object.word1;
object.word2;
object.word3;
Loadash
var array = [['word1', 'word2', 'word3'],[3,5,7],['id1','id2','id3']]
var output = _.reduce(array[0], function (output, word, index) {
output[word] = {count:array[1][index],id:array[2][index]};
return output;
},{});
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}
I am trying to create a new array with just the object values of myArray. My code below returns newArray with both Objects stored, but I am stuck on how to get the 'values' out and put them into the array. I am used to for-in on Objects, but not sure how to access objects when they are stored in an Array.
var myArray = [{first: 'michael', last: 'jordan'}, {first: 'brett', last: 'favre'}];
var myFunc = function (values) {
newArray = [];
for (var i = 0; i < values.length; i += 1) {
newArray.push(values);
}
return newArray;
}
Try this:
var myFunc = function (values) {
newArray = [];
for (var i = 0; i < values.length; i += 1) {
for(var e in values[i]) {
newArray.push(values[i][e]);
}
}
return newArray;
}
Demonstration
Note that this method is 'shallow'—that is, it will only get values one-level deep. If you had a structure like [{foo:{bar:'baz'}}], the result would be [{bar:'baz'}].
Consider this example.
var array = ['a','b','c','d'];
The index of 'a' is 0
The index of 'b' is 1
and so forth...
Therefore:
array[0] = 'a'
Next example:
var array = [ { foo: 'bar' }, { hello: 'world' } ];
The index of the first object is 0
The index of the second object is 1
Therefore:
array[0] = { foo: 'bar' }
To access a property of that object, you can do this:
array[0]['foo'] = 'bar';
So, you can do something like this, to iterate over the members of an object, when that object is inside of an array:
var array = [ { foo: 'bar' }, { hello: 'world' } ],
newArray = [];
var i, len = array.length;
for( i=0; i<len; i++ ) {
for ( e in array[i] ) {
newArray.push(array[i][e]);
}
}
OUTPUT:
newArray = ['bar', 'world'];
This example uses the relatively new Object.keys() and Array.reduce():
var values = myArray.reduce(function(prev, current) {
return prev.concat(Object.keys(current).map(function(key) {
return current[key];
}));
}, []);
I have a returned object list: data.d[15]
and one sample of it:
data.d[3] = {
CityId: 2,
CityName: "Ankara"}
I want to convert it to one object as
cities{
1: "Istanbul",
2: "Ankara",
3: "New York"
}
And it should be generic, so I dont know the "CityId" and "CityName" field names.
what is the best method for it?
thank you all... i have send fieldnames by field object -no dependencies important for this code-, it has been resolved.
var url = this.options.url + "/" + field.values,
id = field.fieldId,
title = field.fieldTitle;
this.getJSON(url, {}, function (rData) {
var obj = {};
for (i = 0; i < rData.d.length; i++)
obj[rData.d[i][id]] = rData.d[i][title];
$("#" + parentId).html(self.getHtmlOfFormData(type, obj));
});
Maybe you need to detect which property contains the name of the city. Maybe something like this can work?
var idprop, nameprop;
for (var prop in data.d[0]) {
if (typeof data.d[0][prop] === "string") nameprop = prop;
if (typeof data.d[0][prop] === "number") idprop = prop;
}
var cities = {};
for (var i = 0; i < data.d.length; i++)
cities[data.d[i][idprop]] = data.d[i][nameprop];
Keep in mind that this works if:
data.d isn't an empty array;
there's just one string property that contains the city name;
there's just one numeric property that contains the city id.
if i understood your question, you are trying to convert some ajax return that looks like this:
data.d = [
{
cityId: someNumber1,
cityName: someName1
},
{
cityId: someNumber2,
cityName: someName2
}
];
into an object that looks like this:
cities = {
someNumber1: someName1,
someNumber2: someName2
};
a snippet like this would do the trick:
var cities = {};
for (var i = 0; i < data.d.length; i++) {
cities[data.d[i].cityId] = data.d[i].cityName;
}