Convert array of objects to Array Angularjs - angularjs

Is there any possible way in angularJs to convert this array of objects:
[{"tickets":1,"month":"june","year":2016},{"tickets":2,"month":"june","year":2015},{"tickets":3,"month":"december","year":2015}]
to an array like this:
[['tickets', 'month','year'], [1, "june",2016],[3, "june",2015],[1, "december",2015]]

Approach using Array#reduce() and Array#concat() that doesn't rely on knowing any of the property names or hard coding resultant array structure
let data = [{"tickets":1,"month":"june","year":2016},{"tickets":2,"month":"june","year":2015},{"tickets":3,"month":"december","year":2015}];
let res = data.reduce((acc, curr) => {
return acc.concat([acc[0].map((key) => curr[key])]);
}, [Object.keys(data[0])]);
console.log(res)

Sure, its pure javascript can handle
var array1 = [{"tickets":1,"month":"june","year":2016},
{"tickets":2,"month":"june","year":2015},
{"tickets":3,"month":"december","year":2015}];
var array2 = [['tickets', 'month','year']];
array1.forEach(function(item){
array2.push([item.tickets, item.month, item.year]);
})
console.log(array2);
UPDATE
More flexible way, adviced by JK_Jha
var array1 = [{"tickets":1,"month":"june","year":2016},
{"tickets":2,"month":"june","year":2015},
{"tickets":3,"month":"december","year":2015}];
var array2 = [Object.keys(array1[0])];
array1.forEach(function(item){
array2.push([item.tickets, item.month, item.year]);
})
console.log(array2);

Related

How can I turn a string into multiple sub arrays in Javascript?

I would like to turn this:
"a:1,b:2,c:3"
Into:
[['a', '1'],['b', '2'],['c', '3']]
Here is the same idea, but a little cooler ;)
let str = "a:1,b:2,c:3";
let result = str.split(',').map(x=>x.split(":"))
console.log(result);
You could use the JavaScript split method here and do it twice.
Something like the following:
let array = [];
let str = "a:1,b:2,c:3";
let splitStr = str.split(',');
splitStr.forEach(subStr => {
array.push(subStr.split(':'));
});
console.log(array);

why add curly braces to the argument 'people' here [duplicate]

I have been reading about Destructuring assignment introduced in ES6.
What is the purpose of this syntax, why was it introduced, and what are some examples of how it might be used in practice?
What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- MDN
Advantages
A. Makes code concise and more readable.
B. We can easily avoid repeated destructing expression.
Some use cases
1. To get values in variable from Objects,array
let obj = { 'a': 1,'b': {'b1': '1.1'}}
let {a,b,b:{b1}} = obj
console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1)
let obj2 = { foo: 'foo' };
let { foo: newVarName } = obj2;
console.log(newVarName);
let arr = [1, 2, 3, 4, 5]
let [first, second, ...rest] = arr
console.log(first, '\n', second, '\n', rest)
// Nested extraction is possible too:
let obj3 = { foo: { bar: 'bar' } };
let { foo: { bar } } = obj3;
console.log(bar);
2. To combine an array at any place with another array.
let arr = [2,3,4,5]
let newArr = [0,1,...arr,6,7]
console.log(newArr)
3. To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}]
let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10}))
console.log(op)
4. To create a shallow copy of objects
let obj = {a:1,b:2,c:3}
let newObj = {...obj}
newObj.a = 'new Obj a'
console.log('Original Object', obj)
console.log('Shallow copied Object', newObj)
5. To extract values from parameters into standalone variables
// Object destructuring:
const fn = ({ prop }) => {
console.log(prop);
};
fn({ prop: 'foo' });
console.log('------------------');
// Array destructuring:
const fn2 = ([item1, item2]) => {
console.log(item1);
console.log(item2);
};
fn2(['bar', 'baz']);
console.log('------------------');
// Assigning default values to destructured properties:
const fn3 = ({ foo="defaultFooVal", bar }) => {
console.log(foo, bar);
};
fn3({ bar: 'bar' });
6. To get dynamic keys value from object
let obj = {a:1,b:2,c:3}
let key = 'c'
let {[key]:value} = obj
console.log(value)
7. To build an object from other object with some default values
let obj = {a:1,b:2,c:3}
let newObj = (({d=4,...rest} = obj), {d,...rest})
console.log(newObj)
8. To swap values
const b = [1, 2, 3, 4];
[b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2
console.log(b);
9. To get a subset of an object
9.1 subset of an object:
const obj = {a:1, b:2, c:3},
subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function
console.log(subset);
9.2 To get a subset of an object using comma operator and destructuring:
const object = { a: 5, b: 6, c: 7 };
const picked = ({a,c}=object, {a,c})
console.log(picked); // { a: 5, c: 7 }
10. To do array to object conversion:
const arr = ["2019", "09", "02"],
date = (([year, day, month]) => ({year, month, day}))(arr);
console.log(date);
11. To set default values in function. (Read this answer for more info )
function someName(element, input,settings={i:"#1d252c", i2:"#fff",...input}){
console.log(settings.i)
console.log(settings.i2)
}
someName('hello', {i:'#123'})
someName('hello', {i2:'#123'})
12. To get properties such as length from an array, function name, number of arguments etc.
let arr = [1,2,3,4,5];
let {length} = arr;
console.log(length);
let func = function dummyFunc(a,b,c) {
return 'A B and C';
}
let {name, length:funcLen} = func;
console.log(name, funcLen);
It is something like what you have can be extracted with the same variable name
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment
var [one, two, three] = ['orange', 'mango', 'banana'];
console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: 'John', age: 32};
console.log(name); // John
console.log(age); // 32
The De-structured assignment of Javascript is probably an inspiration drawn from Perl language.
This facilitates reuse by avoid writing getter methods or wrapper functions.
One best example that I found very helpful in particular was on reusing functions that return more data than what is required.
If there is a function that returns a list or an array or a json, and we are interested in only the first item of the list or array or json,
then we can simply use the de-structured assignment instead of writing a new wrapper function to extract the interesting data item.

how can I combine 2 array to create array of arrays in swift

I have latsArr and LongsArr filled from firebase automatically.
I want to populate latsAndLongsArray in viewDidLoad function. How can I do that?
var latsArr = [1111.0,2222.0,333.0]
var longsArr = [444.0,555.0,666.0]
var latsAndLongs = [[111.0,444.0],[222.0,555.0],[333.0,666.0]]
Use the zip(_:_:) and map(_:) methods combined to get the expected result:
let latsAndLongs = zip(latsArr, longsArr).map { [$0.0, $0.1] }
var latsAndLongs = zip(latsArr, longsArr).map({[$0.0, $0.1]})
One option (which uses tuples instead of arrays) is to use zip.
var latsArr = [1111.0,2222.0,333.0]
var longsArr = [444.0,555.0,666.0]
var latsAndLongs = zip(latsArr, longsArr)
// latsAndLongs == [(1111.0, 444.0), (2222.0, 555.0), (333.0, 666.0)]

ES6: Merge two arrays into an array of objects

I have two arrays that I want to merge together to one array of objects...
The first array is of dates (strings):
let metrodates = [
"2008-01",
"2008-02",
"2008-03",..ect
];
The second array is of numbers:
let figures = [
0,
0.555,
0.293,..ect
]
I want to merge them to make an object like this (so the array items match up by their similar index):
let metrodata = [
{data: 0, date: "2008-01"},
{data: 0.555, date: "2008-02"},
{data: 0.293, date: "2008-03"},..ect
];
So far I do this like so: I create an empty array and then loop through one of the first two arrays to get the index number (the first two arrays are the same length)... But is there an easier way (in ES6)?
let metrodata = [];
for(let index in metrodates){
metrodata.push({data: figures[index], date: metrodates[index]});
}
The easiest way is probably to use map and the index provided to the callback
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = metrodates.map((date,i) => ({date, data: figures[i]}));
console.log(output);
Another option is to make a generic zip function which collates your two input arrays into a single array. This is usually called a "zip" because it interlaces the inputs like teeth on a zipper.
const zip = ([x,...xs], [y,...ys]) => {
if (x === undefined || y === undefined)
return [];
else
return [[x,y], ...zip(xs, ys)];
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = zip(metrodates, figures).map(([date, data]) => ({date, data}));
console.log(output);
Another option is to make a generic map function which accepts more than one source array. The mapping function will receive one value from each source list. See Racket's map procedure for more examples of its use.
This answer might seem the most complicated but it is also the most versatile because it accepts any number of source array inputs.
const isEmpty = xs => xs.length === 0;
const head = ([x,...xs]) => x;
const tail = ([x,...xs]) => xs;
const map = (f, ...xxs) => {
let loop = (acc, xxs) => {
if (xxs.some(isEmpty))
return acc;
else
return loop([...acc, f(...xxs.map(head))], xxs.map(tail));
};
return loop([], xxs);
}
let metrodates = [
"2008-01",
"2008-02",
"2008-03"
];
let figures = [
0,
0.555,
0.293
];
let output = map(
(date, data) => ({date, data}),
metrodates,
figures
);
console.log(output);
If you use lodash, you can use zipWith + ES6 shorthand propery names + ES6 Arrow functions for a one-liner, otherwise see #noami's answer.
const metrodata = _.zipWith(figures, metrodates, (data, date)=> ({ data, date }));

Convert object values into array the Angular way

I have the follow object:
formData : {
_id: "550de8956e2d0948080e220f"
category: "Tag1"
isFeatured: "Yes"
likeCount: 557
title: "Integrating WordPress with Your Website"
}
I tried JavaScript but it returned a null value:
var arryFormData = Array.prototype.slice.call(formData)
How can I convert formData into an array of just its values, not properties?
As in ...
arryFormData = ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
or if You like to more functional code:
var arr = [];
angular.forEach(obj, function(value, key){
arr.push(value);
});
If you are using underscore.js,
_.values(formData)
// will get ["550de8956e2d0948080e220f", "Tag1", "Yes", 557, "Integrating WordPress with Your Website"]
See: here
Alternatively:
var res = [];
for (var x in formData){
formData.hasOwnProperty(x) && res.push(formData[x])
}
console.log(res);
In any event, the array elements might not be in the order that you want.
I prefer one line solution with Object.keys() and es6 syntax, until Object.values() is not here
const values = Object.keys(obj).map(it => obj[it])
or in es5
var values = Object.keys(obj).map(function(it) {
return obj[it]
})
I think there's No magic way, you just have to use a for loop:
for (var key in obj) {
values.push(obj[key])
}
To make it angular, you could use angular.forEach I guess...
This is how i have handled in Angular 5 to convert Object into Array as API gives response in JSON Object so we can convert it into array to use it.
let tmepArr = {};
Object.keys(res).forEach( key => {
tmepArr['name'] = [res[key].name];
tmepArr['id'] = [res[key].id];
});
this.marketplaceDropDown = [tmepArr];

Resources