Copy Array from http request to other array in Angular - arrays

I pretty new to angular and I have a question.
I need 2 arrays for ng2-charts, one with labels and one with data.
I make http request to AWS and I got this json
{
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
I assing all the result to result: Array<SystemModel>;
For use speed and time on ng2-charts I have to copy the two array speed and time on new array: public lineChartSpeed: Array<number> = []; and public lineChartTime: Array<any> = [];
How can I copy this 2 array on my new array? I know how to access to data only on html template, but not on typscript file...
My component is:
public lineChartSpeed: Array<number> = [];
lineChartTime: Array<any> = [];
result: Array<ImpiantoModel>;
getdata() {
this.http.get<SystemModel[]>(this.myUrl)
.subscribe(
data => { this.result = data;
// perform the copy of speed and time on lineChartTime and lineChartSpeed
});
}
How can I copy the array?
If you need more details, please ask in the comments!
thank you !

var system1 = {
"System1": [
{
"name": "MF3",
"descr": "Multifilo MF3",
"speed": [1,2,3,4],
"time": ["10.01", "10.02", "10.03", "10.04"]
}
]
}
var speed = system1.System1[0].speed
var time = system1.System1[0].time
console.log('Array of Speed', speed)
console.log('Array of Time', time)
//Merge or concatenate two Arrays
var newArray = [...speed, ...time]
console.log('Merged or concatenated Arrays', newArray)

Use slice operator to create a new copy of the array
this.result = data.slice();

this.lineChartSpeed = [].concat(this.result[0].speed);
this.lineChartTime = [].concat(this.result[0].time);

Related

Best way to edit an item in an array

I have an array of custom class and I want to make a change to one of the items in it.
var mainArray = [MainOrder]()
//Now imagine that mainArray has a bunch of different items in it.
struct MainOrder:Codable {
var time:Date?
var order_id:String?
var side:String?
}
What is the best way to do that? Right now I find the index then I move it into a new variable then I delete the item from the array and then add it back again like you see below. But I am sure this is better way to do this.
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
var tempVar = self.mainArray[tempIndex]
tempVar.time = Date()
self.mainArray.remove(at: tempIndex)
self.mainArray.insert(tempVar, at: tempIndex)
}
You just need the following:
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
mainArray[tempIndex].time = Date()
}
Here's a complete example demonstrating that this works:
struct MainOrder:Codable,CustomStringConvertible {
var time:Date?
var order_id:String?
var side:String?
var description: String {
return "time: \(time), order_id: \(order_id), side: \(side)"
}
}
var mainArray = [MainOrder]()
mainArray.append(MainOrder(time: nil, order_id: "hi", side: "left"))
print(mainArray)
if let tempIndex = self.mainArray.index(where: {$0.side == "left"}) {
mainArray[tempIndex].time = Date()
}
print(mainArray)
Output:
[time: nil, order_id: Optional("hi"), side: Optional("left")]
[time: Optional(2018-01-13 01:59:06 +0000), order_id: Optional("hi"), side: Optional("left")]
If you can guarantee there will always be an object in the array with the matching side value, you can force this all into one line:
mainArray[mainArray.index(where: { $0.side == "left" })!].time = Date()
But this will crash if your assumption is wrong. Be safe and do with the if let.
Declare it as class so it will be reference type
class MainOrder:NSObject,Codable {
var time:Date?
var order_id:String?
var side:String?
}
Edit item directly
var tempVar = self.mainArray[tempIndex]
tempVar.time = Date()

How dynamically transform my "Object" to List in ng-model at view

I'm trying to transform my object to list dynamically, so I'm building at view instead of declaring at controller.
I don't want to declare like this: custom_fields.title_field.type_text_field = [] because the title_field is built dynamic, it could be any kind of text like full_name
My json as is:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":{
"name":"John",
"first_name":"Wick"
},
"type_boolean_field":{
"is_badass": true,
"is_good_movie": true
},
"type_select_field": {
"this_select": 1,
"i_got_this": "nope i didnt got this"
}
},
And to be:
"custom_fields":{
"title_dynamic_generate_field":{
"type_text_field":[{
"name":"John",
"first_name":"Wick"
}],
"type_boolean_field":[{
"is_badass": true,
"is_good_movie": true
}],
"type_select_field": [{
"this_select": 1,
"i_got_this": "nope i didnt got this"
}]
},
the object I'm trying to transform into array is type_text_field which can be dynamic too, like type_date_field or type_select_field and so on.
My ng-model is like this:
ng-model="objectApp.application.applicant.custom_fields[layout.dynamic_title][input.type][input.variable]"
the [input.type] is that I'm trying to transform into array, how can I achieve this? I tried to use $index, but got strange results.
We can do it by 2 solutions:
There is a question about your task:
? how you want handle if we have more than one type_text_field in title_dynamic_generate_field? because you want to convert it to "type_text_field":[{},...]
however my answers about the question are:
If we know what's the dynamic params which we want to send theme as json, i mean if we know what is the key of title_dynamic_generate_field or type_text_field, we do as this sample:
var data = {
"custom_fields": {
dynamicParamIs1: 'title_dynamic_generate_field',
dynamicParamIs2: 'type_text_field',
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var paramHelper1 = json.custom_fields[json.custom_fields.dynamicParamIs1];
var paramHelper2 = json.custom_fields.dynamicParamIs2;
var solutionA = function (object, as) {
var array = [];
for (var key in object) {
var newObject = object[key];
array.push(newObject);
}
object[as] = array;
}
solutionA(paramHelper1, paramHelper2);
We changed a model of our json which can help us to detect (find) the keys
If we don't know what is the dynamic params are, we do as this:
var data = {
"custom_fields": {
"title_dynamic_generate_field": {
"type_text_field": {
"name": "John",
"first_name": "Wick"
}
}
}
}
var solutionB = function (json) {
var array = [];
for (var key in json) {
var j1 = json[key];
for (var key2 in j1) {
var j2 = j1[key2];
for (var key3 in j2) {
var fullObject = j2[key3];
array.push(fullObject);
j2[key3] = array;
}
}
}
}
solutionB(data);
This sample is manual which we use nested for to detect the keys name

Reduce array to set in Swift

I am trying to reduce an array of objects to a set in Swift and this is my code:
objects.reduce(Set<String>()) { $0.insert($1.URL) }
However, I get an error:
Type of expression is ambiguous without more context.
I do not understand what the problem is, since the type of URL is definitely String. Any ideas?
You don't have to reduce an array to get it into a set; just create the set with an array: let objectSet = Set(objects.map { $0.URL }).
With Swift 5.1, you can use one of the three following examples in order to solve your problem.
#1. Using Array's map(_:) method and Set's init(_:) initializer
In the simplest case, you can map you initial array to an array of urls (String) then create a set from that array. The Playground below code shows how to do it:
struct MyObject {
let url: String
}
let objectArray = [
MyObject(url: "mozilla.org"),
MyObject(url: "gnu.org"),
MyObject(url: "git-scm.com")
]
let urlArray = objectArray.map({ $0.url })
let urlSet = Set(urlArray)
dump(urlSet)
// ▿ 3 members
// - "git-scm.com"
// - "mozilla.org"
// - "gnu.org"
#2. Using Array's reduce(into:_:) method
struct MyObject {
let url: String
}
let objectArray = [
MyObject(url: "mozilla.org"),
MyObject(url: "gnu.org"),
MyObject(url: "git-scm.com")
]
let urlSet = objectArray.reduce(into: Set<String>(), { (urls, object) in
urls.insert(object.url)
})
dump(urlSet)
// ▿ 3 members
// - "git-scm.com"
// - "mozilla.org"
// - "gnu.org"
As an alternative, you can use Array's reduce(_:_:) method:
struct MyObject {
let url: String
}
let objectArray = [
MyObject(url: "mozilla.org"),
MyObject(url: "gnu.org"),
MyObject(url: "git-scm.com")
]
let urlSet = objectArray.reduce(Set<String>(), { (partialSet, object) in
var urls = partialSet
urls.insert(object.url)
return urls
})
dump(urlSet)
// ▿ 3 members
// - "git-scm.com"
// - "mozilla.org"
// - "gnu.org"
#3. Using an Array extension
If necessary, you can create a mapToSet method for Array that takes a transform closure parameter and returns a Set. The Playground below code shows how to use it:
extension Array {
func mapToSet<T: Hashable>(_ transform: (Element) -> T) -> Set<T> {
var result = Set<T>()
for item in self {
result.insert(transform(item))
}
return result
}
}
struct MyObject {
let url: String
}
let objectArray = [
MyObject(url: "mozilla.org"),
MyObject(url: "gnu.org"),
MyObject(url: "git-scm.com")
]
let urlSet = objectArray.mapToSet({ $0.url })
dump(urlSet)
// ▿ 3 members
// - "git-scm.com"
// - "mozilla.org"
// - "gnu.org"
reduce() method expects a closure that returns a combined value, while insert() methods of Set value does not return anything but instead it inserts a new element into the existing set.
In order to make it work you would need to do something like:
objects.reduce(Set<String>()) {
$0.union(CollectionOfOne($1.URL))
}
But the above is a bit of an unnecessary complication. If you have a big array, that would mean quite a number of ever-growing sets to be created while Swift goes over all the elements from objects. Better follow the advice from #NRitH and use map() as that would make a resulting set in one go.
Swift 1.0-2.x ONLY:
If URL on your object is a strongly-typed String, you can create a new Set<String> object and use unionInPlace on the set with the mapped array:
var mySet = Set<String>()
mySet.unionInPlace(objects.map { $0.URL as String })

How to push some data from Json into new array in AngularJS?

Let's say I have this Json ..
{
"name": "Mark",
"gender": "male",
"account1": {
"accountNo": 1201,
"balance": 300
},
"account2": {
"accountNo": 1354,
"balance": 5000
}
}
What I expect is like ..
$scope.myArray = [
{
"accountNo": 1201,
"balance": 300
},
{
"accountNo": 1354,
"balance": 5000
}
];
In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).
You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.
Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply
$scope.myArray = json.accounts;
However, as noted, you do not have an accounts array so you need to make one.
var accounts = [];
for(var key in json){
if( !json.hasOwnProperty(key) // skip prototype extensions
|| !json[key].hasOwnProperty("accountNo") //skip non account objects
) continue;
accounts.push(json[key]);
}
And now you may use this array
$scope.myArray = accounts;
You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(foo['account'+i]);
}
Although, this has nothing to do with angularjs.

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