Convert Array of Javascript Objects to single simple array - javascript

I have not been able to figure out how to properly accomplish this.
I have a JS array of objects that looks like this:
[{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}]
I would like to convert this into a simple, single JS array, without any of the keys, it should look like this:
[
"09599",
"KCC",
"000027",
"Johns" ]
The IDs can be dropped entirely. Any help would be really appreciated.

Simply iterate the original array, pick the interesting keys and accumulate them in another array, like this
var keys = ['num', 'name'],
result = [];
for (var i = 0; i < data.length; i += 1) {
// Get the current object to be processed
var currentObject = data[i];
for (var j = 0; j < keys.length; j += 1) {
// Get the current key to be picked from the object
var currentKey = keys[j];
// Get the value corresponding to the key from the object and
// push it to the array
result.push(currentObject[currentKey]);
}
}
console.log(result);
// [ '09599', 'KCC', '000027', 'Johns' ]
Here, data is the original array in the question. keys is an array of keys which you like to extract from the objects.
If you want to do this purely with functional programming technique, then you can use Array.prototype.reduce, Array.prototype.concat and Array.prototype.map, like this
var keys = ['num', 'name'];
console.log(data.reduce(function (result, currentObject) {
return result.concat(keys.map(function (currentKey) {
return currentObject[currentKey];
}));
}, []));
// [ '09599', 'KCC', '000027', 'Johns' ]

You can use Object.keys() and .forEach() method to iterate through your array of object, and use .map() to build your filtered array.
var array = [{"num":"09599","name":"KCC","id":null},{"num":"000027","name":"Johns","id":null}];
var filtered = array.map(function(elm){
var tmp = [];
//Loop over keys of object elm
Object.keys(elm).forEach(function(value){
//If key not equal to id
value !== 'id'
//Push element to temporary array
? tmp.push(elm[value])
//otherwise, do nothing
: false
});
//return our array
return tmp;
});
//Flat our filtered array
filtered = [].concat.apply([], filtered);
console.log(filtered);
//["09599", "KCC", "000027", "Johns"]

How about using map :
var data = [
{"num":"09599","name":"KCC","id":null}
{"num":"000027","name":"Johns","id":null}
];
var result = data.map(function(obj) {
return [
obj.num,
obj.name,
obj.id
];
});

Related

How to iterate over objects in an array?

I have an array object as mentioned below;
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
I would like to extract the values of dateformat into a separate array, e.g.:
var dateArray=["apr1","apr2","apr3"];
var score=[1,2,3];
I am using a for loop to extract the index but I'm not able to get the values.
Use map to iterate over the initial array objects and return the item you want.
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
var dateArray = myArray.map(function(obj){return obj.dateformat;}),
score = myArray.map(function(obj){return obj.score});
console.log(dateArray);
console.log(score);
Here's the answer as a simple loop.
var dateArray = new Array(myArray.length);
for(var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
var dateValue = value.dateformat;
dateArray[i] = dateValue;
}
You can accomplish the same using the map function:
var dateArray = myArray.map(function(value) { return value.dateformat; });
Create the empty arrays, and use forEach with an argument of 'element' (which represents each object in the array) and push esch of the properties of each object into the required array.
var dateArray=[];
var score=[];
var myArray=[
{dateformat:"apr1", score:1},
{dateformat:"apr2",score:2},
{dateformat:"apr3",score:3}
];
myArray.forEach(function(element) {
dateArray.push(element.dateformat);
score.push(element.score);
});
console.log(dateArray); //gives ["apr1","apr2","apr3"]
console.log(score); //gives ["1","2","3"]
You could use a single loop approach of the given array and iterate the keys and push the values to the wanted arrays.
var myArray = [{ dateformat: "apr1", score: 1 }, { dateformat: "apr2", score: 2 }, { dateformat: "apr3", score: 3 }],
dateArray = [],
score = [];
myArray.forEach(function (target, keys) {
return function(a) {
keys.forEach(function(k, i) {
target[i].push(a[k]);
});
};
}([dateArray, score], ['dateformat', 'score']));
console.log(dateArray);
console.log(score);
If only you don't want to hard code the variables, you could use Array#forEach and Object.keys to store each unique key values inside e.g. array.
Note: It doesn't matter how many keys do you have in your objects, following solution will always return you the right output. Mind that you don't even have to initially declare new variables.
var myArray = [{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}],
obj = {};
myArray.forEach(v => Object.keys(v).forEach(function(c) {
(obj[c] || (obj[c] = [])).push(v[c]);
}));
console.log(obj);

Combining elements of 2 dimentional array

I have an JavaScript array:
var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];
I want final array to look like:
var final = [["A",[["05",90],["04",240],["03",235]]],["B",[["00",123],["01",234]]]];
The final array is formed by combining all the 2nd element of 2 dimensional array when the 1st element matches.
Please advice how can this be achieved in JavaScript
Object keys are generally the easiest way to create groups like this
var tmp = {}; // temporary grouping object
// loop over data
arr.forEach(function (item) {
// check if group started
if (!tmp.hasOwnProperty(item[0])) {
tmp[item[0]] = [];
}
// push data to group
tmp[item[0]].push(item[1]);
});
// map temp object to results array
var results = Object.keys(tmp).map(function (key) {
return [key, tmp[key]];
});
DEMO
If you start with the array you gave:
var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];
then create a new array to store the values:
var final = [];
and simply combine all of the third-level elements (such as ["05",90] and ["01",234]) of each second-level ones (such as "A" and "B") by looping through the array:
for(var i = 0; i < arr.length; i++) {
var found = false;
for(var j = 0; j < final.length; j++) {
if(arr[i][0] == final[j][0]) {
final[j][1].push(arr[i][1]);
found = true;
break;
}
}
if(!found) {
final[final.length] = [arr[i][0], [[arr[i][1][0], arr[i][1][1]]]];
}
}
This is essentially a sorting method: if the "key" is equal to one in the final array, then it adds it to that one. If not, then appends it to the end of final.
Here's the working example on JSFiddle: link.
This outputs the array:
["A", [["05", 90], ["04", 240], ["03", 235]]], ["B", [["00", 123], ["01", 234]]]
as requested.
Also, as #PaulS commented, it would be recommended to use Objects instead as Strings, to make them Key-Value pairs. But in my answer I stuck with arrays.

What is better way to send associative array through map/reduce at MongoDB?

Here is my functions:
map:
function () {
// initialize KEY
// initialize INDEX (0..65536)
// initialize VALUE
var arr = [];
arr[INDEX] = { val: VALUE, count: 1 };
emit(KEY, { arr: arr });
}
reduce:
function (key, values) {
var result = { arr: [] };
for (var i = 0; i < values.length; i++) {
values[i].arr.forEach(function (item, i) {
if (result.arr.hasOwnProperty(i)) {
result.arr[i].val += item.val;
result.arr[i].count += item.count ;
} else {
result.arr[i] = item;
}
});
}
As you can see, I'm trying to send associative array from map to reduce. But when I try to enumerate values of array values[i].arr.forEach I get listing 0..max_index. So, every reduce I have to enumerate a lot of undefined elements.
When I try to enumerate values of array (arr) at map I get expected result (only defined elements).
Actually, I don't sure that associative array is best solution for my task. But I can't find faster way to find element by id.
Could you please answer the questions:
Why differences of array processing at map and
reduce?
What data structure I should use (or how I should use my array) to optimize my current solution?
I decided to use object:
var arr = {};
arr[INDEX] = { val: VALUE, count: 1 };
It is works with for .. in as expected.

How do you search object for a property within property?

I have this object:
key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
And I have an array with only types and I need to add the given image to it, the array looks something like this:
[{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}]
Basically I want to loop the array, find the type in the key object and get the given image and save it into the array.
Is there any simple way to do this?
One thing that stands out here for me is the line
...get the given image and save it into the array
I'm assuming this means the original array. I think a better approach would be to map the appropriate keys and values to a new array but I've assumed, for this example, that it's a requirement.
In an attempt to keep the solution as terse as possible and the request for a lodash solution:
_.each(key, function(prop){
_.each(_.filter(types, { type: prop.type }), function(type) { type.image = prop.img });
});
Given the object of keys and an array of objects like so:
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var arr = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
We can first create an array of the properties in the object key to make iterating it simpler.
Then loop over the array arr, and upon each member, check with a some loop which image belongs to the member by its type (some returning on the first true and ending the loop).
You can change the forEach to a map (and assign the returned new array to arr or a new variable) if you want the loop to be without side-effects, and not to mutate the original array.
var keyTypes = Object.keys(key);
arr.forEach(function (item) {
keyTypes.some(function (keyType) {
if (key[keyType].type === item.type) {
item.image = key[keyType].img;
return true;
}
return false;
});
});
The smarter thing would be to change the object of the imagetypes so that you could use the type as the accessing property, or create another object for that (as pointed out in another answer).
I'm not sure if this solution is modern, but it does not use any loops or recursion.
object = {
spawn: {type:1, img:app.assets.get('assets/spawn.svg')},
wall: {type:2, img:app.assets.get('assets/wall.svg')},
grass: {type:3, img:app.assets.get('assets/grass.svg')},
spike: {type:4, img:app.assets.get('assets/spike.svg')},
ground: {type:5, img:app.assets.get('assets/ground.svg')}
};
arr = [
{type:1, image:null},
{type:3, image:null},
{type:2, image:null},
{type:2, image:null},
{type:5, image:null}
];
var typeImages = {};
Object.getOwnPropertyNames(object).forEach(function(value){
typeImages[object[value].type] = object[value].img;
});
arr = arr.map(function(value){
return {
type: value.type,
image: typeImages[value.type]
};
});
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var typesArray = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
for(var i = 0, j = typesArray.length; i < j; i++)
{
typesArray[i].image = getKeyObjectFromType(typesArray[i].type).img;
}
function getKeyObjectFromType(type)
{
for(var k in key)
{
if(key[k].type == type)
{
return key[k];
}
}
return {};
}
for (var i = 0; i < typesArray.length; i++) {
for (prop in key) {
if (key[prop].type === typesArray[i].type) {
typesArray[i].image = key[prop].img;
}
}
}
It loops through the array ("typesArray"), and for each array item, it go through all the objects in key looking for the one with the same "type". When it finds it, it takes that key object's "img" and saves into the array.
Using lodash (https://lodash.com/):
var key = {
spawn:{type:1,img:app.assets.get('assets/spawn.svg')},
wall:{type:2,img:app.assets.get('assets/wall.svg')},
grass:{type:3,img:app.assets.get('assets/grass.svg')},
spike:{type:4,img:app.assets.get('assets/spike.svg')},
ground:{type:5,img:app.assets.get('assets/ground.svg')}
};
var initialList = [{type:1,image:null},{type:3,image:null},{type:2,image:null},{type:2,image:null},{type:5,image:null}];
var updatedList = _.transform(initialList, function(result, item) {
item.image = _.find(key, _.matchesProperty('type', item.type)).img;
result.push(item);
});
This will go over every item in the initialList, find the object that matched their type property in key and put it in the image property.
The end result will be in updatedList

What kind of array is this in JavaScript?

I have an array that looks like this:
var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];
I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.
var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
//add to my newArray like this : ['title1','description1'],['title3','description3']
?
}
How can I do it?
Try like below,
var newArray = [];
for (var i = 0; i < locationsArray.length; i++) {
if (parseInt(locationsArray[i][2], 10) > 10) {
newArray.push([locationsArray[i][0], locationsArray[i][1]]);
}
}
DEMO: http://jsfiddle.net/cT6NV/
It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.
For instance, if I retrieve locationsArray[0] I get ['title1','description1','12']. If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1'.
Completing your example:
var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}
throw that in a loop and you're good to go.
It's an array of arrays of strings.
Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).
So, if we take the following example :
var myArray = ["string", "string2", ["string3-1", "string3-2"]];
The values would be as such :
myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"
There can be as many levels of depth as your RAM can handle.
locationsArray is an array of arrays. The first [] operator indexes into the main array (e.g. locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (e.g. locationsArray[0][1] = 'description1').
Your newArray looks like it needs to be the same thing.
It's an array of array.
var newArray = [];
var locationsArray = [
['title1','description1','12'],
['title2','description2','7'],
['title3','description3','57']
];
for(i = 0; i < locationsArray.length; i++) {
if (locationsArray[i][2] > 10) {
newArray .push([locationsArray[i][0], locationsArray[i][1]]);
}
}
console.log(newArray );

Categories

Resources