convert array of objects into simple array nodejs - javascript

I am creating project using nodejs. I want to convert array of objects into simple array.For example
var test = [ { id: '1111',
type: 'sdfsdf'
},
{ id: 'df45',
type: 'fsdsdf',
}]
I need
var actual = [111,'sdfsdf'], ['df45','fsdsdf'].

I would propose this solution based on a dynamic number of keys:
var arr = test.map(function(obj){
return Object.keys(obj). // convert object to array of keys
reduce(function(arr, current){arr.push(obj[current]); return arr}, []); // generate a new array based on object values
});

This can be done using Array.map() as follows:
var actual = []
test.map(function(object) {
actual.push(objectToArray(object))
})
function objectToArray(obj) {
var array = []
// As georg suggested, this gets a list of the keys
// of the object and sorts them, and adds them to an array
var obj_keys = Object.keys(obj).sort()
// here we iterate over the list of keys
// and add the corresponding properties from the object
// to the 'array' that will be returned
for(var i = 0; i < obj_keys.length; i++) {
array.push(obj[obj_keys[i]])
}
return array
}
The function objectToArray takes any object and turns it into an array so that it can be flexible regardless of the keys within the object.

Related

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

pushing strings into an object

I have an array of objects and an array of string and I am tying to combine the two in sequence meaning I would like to first item on the array to be stored only in the first object, second item of the array only in the second object, ect. Something like the following.
var objects = [ obj1, obj2, obj3];
var strings = ["123", "456", "789"];
//Result
var results = [
{
"obj1": {
number: "123"
},
{
"obj2": {
number: "456"
},
{
"obj2": {
number: "789"
}
];
I have been trying to do this with a push and a for loop but I seem to end up with each object containing all three strings.
Its easy:-
for (var i = 0; i < objects.length; i++) {// start loop for getting values one by one from object array
objects[i].number = strings[i]; // assign string values to object array values
}
Matched object and string share the same array index:
for (var i = 0; i < objects.length; i++) {
objects[i].number = strings[i];
}
Or you could do this using the map function:
var results = objects.map(function (value, index) {
return Object.assign({}, value, { number: strings[index] });
});
The other answers are good I just wanted to give you another way. This way you also do not modify the existing objects array
In case you don't know Object.assign add to the first argument (in our case the empty object {}) all the properties from the other object arguments. You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Also, you can learn here about the map function: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Convert Array of Javascript Objects to single simple array

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
];
});

Convert array of javascript objects to JSON

I have a set of data in the format:
[{"title":movietitle1, "id":445, "release":"16JUN1985"}, {"title":movietitle2, "id":487, "release":"12AUG1993"}]
Which I need to convert into JSON formatted as such:
{
"movietitle1":{"id":445,"release":"16JUN1985"},
"movietitle2":{"id":487, "release":"12AUG1993"}
}
I don't have any idea of how to make this happen.
You can do this with JSON.stringify() and some basic data manipulation.
Store your data in a variable, lets call it input_data.
Loop through your data and use each entry to build up another variable, lets call it output_data.
// create an object to store the newly formatted data
var output_data = {};
// the code in here is run once for each item in input_data
for (var i = 0; i < input_data.length; i++) {
// get the current item's title
var title = input_data[i].title;
// use the title as the key in the output data
// and assign the other values to that key
output_data[title] = {
id: input_data[i].id,
release: input_data[i].release
};
}
// use JSON.stringify() to make a valid JSON string
var json = JSON.stringify(output_data);
// now use the variable json which contains your JSON string
What you are asking for is to turn an array into a map , keying by a specific property, If you really want JSON, you can just call JSON.stringify on the resulting JS object.
http://jsfiddle.net/FfE8f/1/
/**
* Given an array and a property name to key by, returns a map that is keyed by each array element's chosen property
* This method supports nested lists
* Sample input: list = [{a: 1, b:2}, {a:5, b:7}, [{a:8, b:6}, {a:7, b:7}]]; prop = 'a'
* Sample output: {'1': {a: 1, b:2}, '5': {a:5, b:7}, '8': {a:8, b:6}, '7':{a:7, b:7}}
* #param {object[]} list of objects to be transformed into a keyed object
* #param {string} keyByProp The name of the property to key by
* #return {object} Map keyed by the given property's values
*/
function mapFromArray (list , keyByProp) {
var map = {};
for (var i=0, item; item = list[i]; i++) {
if (item instanceof Array) {
// Ext.apply just copies all properties from one object to another,
// you'll have to use something else. this is only required to support nested arrays.
Ext.apply(map, mapFromArray(item, keyByProp));
} else {
map[item[keyByProp]] = item;
}
}
return map;
};
console.log(mapFromArray([
{"title": "title 1", "id":445, "release":"16JUN1985"},
{"title":"movietitle2", "id":487, "release":"12AUG1993"}],
"title"
)));
// outputs
{
"title 1": {"title":"title 1","id":445,"release":"16JUN1985"},
"movietitle2": {"title":"movietitle2","id":487,"release":"12AUG1993"}
}
See More efficient way to search an array of javascript objects?
Your mixing terms. I'm assuming you're asking about manipulating data with JavaScript objects and not strings with JSON data. (The later can be converted with JSON.parse).
First iterate over the array and assigning to an object. This kind of data manipulation works well using Underscore, check it out.
In vanilla JS lets try something like this:
var newData = {};
data.forEach(function(item) {
var title = item.title;
delete item.title;
newData[title] = item;
});
A little crufty but gets the job done.
Personally I'd use this Underscore version:
var newData = _(data).chain()
.map(function(item) {
return [item.title, _(item).omit('title')];
})
.object()
.value();

Sort complex JSON based on particular key

I have a JSON object with the following format:
{
items:{
nestedObj:{
position:3
},
nestedObj2:{
position:1
},
nestedObj3:{
position:2,
items:{
dblNestedObj:{
position:2
},
dblNestedObj2:{
position:3
},
dblNestedObj3:{
position:1
}
}
}
}
}
I am attempting to sort each level of nested object by their position attribute. I can recursively iterate the object, but I don't know where to start for sorting it...
Unfortunately it's not quite so easy to use the sort method as it would if you had an array. So let's build an array:
var tmp = [], x;
for( x in obj.items) { // assuming your main object is called obj
tmp.push([x,obj.items[x].position]);
// here we add a pair to the array, holding the key and the value
}
// now we can use sort()
tmp.sort(function(a,b) {return a[1]-b[1];}); // sort by the value
// and now apply the sort order to the object
var neworder = {}, l = tmp.length, i;
for( i=0; i<l; i++) neworder[tmp[i][0]] = obj.items[tmp[i][0]];
obj.items = neworder;

Categories

Resources