AngularJS objects in an array to new one [duplicate] - javascript

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
DashboardService.GetDateList($scope.datestart, $scope.dateend).then(function (response) {
$scope.listdate = response.data;
});
i get an array list from this function above
[{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}
how can i push all day value from this array into a new one.

You can use Array#map to get the value of every day key.
var arr = [{"day":1,"sql_date":"2017-04-01T00:00:00"},{"day":2,"sql_date":"2017-04-02T00:00:00"},{"day":3,"sql_date":"2017-04-03T00:00:00"},{"day":4,"sql_date":"2017-04-04T00:00:00"},{"day":5,"sql_date":"2017-04-05T00:00:00"}],
newArr = arr.map(v => v.day);
console.log(newArr);

You can achieve this in different ways :
Using JavaScript for...in loop.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = [];
for (var i in responseObj) {
newArr.push({"day":responseObj[i].day});
}
console.log(newArr);
Using Array map() method.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = responseObj.map(function(item) {
return {"day":item.day};
});
console.log(newArr);
Using JavaScript for loop.
DEMO
var responseObj = [{"day":1,"sql_date":"2017-04-01T00:00:00"},
{"day":2,"sql_date":"2017-04-02T00:00:00"},
{"day":3,"sql_date":"2017-04-03T00:00:00"},
{"day":4,"sql_date":"2017-04-04T00:00:00"},
{"day":5,"sql_date":"2017-04-05T00:00:00"}];
var newArr = [];
for (var i = 0; i < responseObj.length; i++) {
newArr.push({"day": responseObj[i].day});
}
console.log(newArr);

Still you can use map instead of for loop. Please find the code snippet below
var arr = [{"day":1,"sql_date":"2017-04-01T00:00:00"},{"day":2,"sql_date":"2017-04-02T00:00:00"},{"day":3,"sql_date":"2017-04-03T00:00:00"},{"day":4,"sql_date":"2017-04-04T00:00:00"},{"day":5,"sql_date":"2017-04-05T00:00:00"}],
newArr = arr.map(function(obj) { return obj.day });
console.log(newArr);

Related

I want to convert array to object [duplicate]

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
JS : Convert Array of Strings to Array of Objects
(1 answer)
Convert array of strings into an array of objects
(6 answers)
Closed 3 years ago.
What is the best way to convert:
from
['firstName','lastName','gender']
to
0: {title: "firstName"}
1: {title: "lastName"}
2: {title: "gender"}
in JavaScript
You can use .map() to get the desired output:
const data = ['firstName','lastName','gender'];
const result = data.map(name => ({ title: name }));
console.log(result);
Try this code.I hope it will helps you.
var arr = ['firstName','lastName','gender']
var jsonObj = {};
for (var i = 0 ; i < arr.length; i++) {
jsonObj['title' +(i+1) ] = arr[i];
}
console.log(jsonObj)
You can simply use forEach() loop which is the easiest way:
var arr = ['firstName','lastName','gender'];
let res = [];
arr.forEach((item) => res.push({title: item}));
console.log(res);
Just to build your knowledge in Array operations you can also use reduce():
var arr = ['firstName','lastName','gender'];
let res = arr.reduce((acc, item) => {
acc.push({title: item});
return acc;
}, []);
console.log(res);

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

Sorting Array based on another array [duplicate]

This question already has an answer here:
javascript sorting array based on another array
(1 answer)
Closed 6 years ago.
I have an array that could be made up of any the following values:
input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
'input' can be made of any # of these values, without any duplicates. I'm trying to figure out how to sort 'input' according to the order of 'sortingArray':
sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
Any help would be greatly appreciated.
You can also use filter function and get copy of sortingArray including only values from input:
var input = ['S-1','S-2','S-3','S-4','S-5'];
var sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
var result = sortingArray.filter((el)=>(input.indexOf(el) > -1));
console.log(JSON.stringify(result));
Build a look-up object from your "sorting array":
var indexes = sortingArray.reduce(function(lookup, key, index) {
lookup[key] = index;
return lookup;
}, {});
Now you can use that in a comparator function:
input.sort(function(k1, k2) {
return indexes[k1] - indexes[k2];
});
Simple use with for loop.And apply the if condition for half of the array length.Then pass with new array
var input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
var c =eval(input.length/2);
arr=[];
for(var i=0; i<input.length; i++){
if(i < c)
{
arr.push(input[i]);
arr.push(input[i+c]);
}
}
console.log(arr)
You could use an object with the indices of the sorted array and sort the new array with it.
var input = ['S-1', 'S-2', 'S-3', 'S-4', 'S-5', 'S-6', 'S-7', 'S-8'],
sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"],
order = Object.create(null);
sortingArray.forEach(function (a, i) { order[a] = i; });
input.sort(function (a, b) { return order[a] - order[b]; });
console.log(input);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

Returning only certain properties from an array of objects in Javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)

Categories

Resources