I'am trying make an array of object.
var number = 0;
var name = 1;
var dKeyObj = new Object();
//var dKeyPiar = new Object();
var dKeyPiar = [];
function sendFakeData() {
request(options, function (error, resp, body) {
dKeyObj['name'] = name.toString(16).padStart(2, '0'); // hexa value
dKeyObj['value'] = resp.headers['value'];
dKeyPair[number++] = dKeyObj;
console.log(dKeyPair[0]);
if(number < 99)
making();
else
//console.log('lasted data ' + dKeyPair[10]['name']);
console.log('lasted data ' + dKeyPair[10]);
});
}
I think the result is...
{ name: '01', value: 'the first value'}
{ name: '01', value: 'the first value'}
{ name: '01', value: 'the first value'}
...
//latest data 0a
latest data { name: '0a', value: 'the tenth value'}
But the log is...
{ name: '01', value: 'the first value'}
{ name: '02', value: 'the second value'}
{ name: '03', value: 'the third value'}
...
//latest data 63
latest data [object, Object]
The index of dKeyPair is ignored.
Can I make an array of object?
var array = [];
var obj = {};
obj["name"] = "name";
obj["value"] = "val";
array.push(obj);
To push an object into an array we do the above.
You can objects into array:
var dKeyObj1 = {'k1':'v1'};
var dKeyObj2 = {'k2':'v2'};
var arr = new Array();
arr.push(dKeyObj1);
arr.push(dKeyObj2);
Related
I have two formatted array as below code, and I would like to match the id and get the matched id value of size and stock
I have the code from github as below but can not get it to work
var arraysize = [];
var arraycode = [];
var code = '{id:'+stock[i][1] +',stock:'+ stock[i][4]+'}';
var size = '{id:'+tomatchcode+',size:'+tomatchsize+'}';
arraycode[i] = code;
arraysize[i] = size;
Logger.log(arraysize);
Logger.log(arraycode);
[19-08-29 10:32:35:003 ICT] [{id:59,size:36}, {id:123,size:37}, {id:62,size:38}, {id:63,size:39}, {id:64,size:40}]
[19-08-29 10:32:35:003 ICT] [{id:63,stock:17}, {id:123,stock:16}, {id:59,stock:10}, {id:64,stock:12}, {id:62,stock:14}]
//both array id value in random position but have same value
var matcharray =checkArrayForMatches(arraycode,arraysize)
function checkArrayForMatches(array,properties){
var returnArray = [];
if (Array.isArray(array[0])){
for (var i = 0,x = array.length;i<x;i++){
var row = array[i];
var match = true;
for (var j in properties){
if (properties[j] !== row[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
} else if (typeof array[0] == 'object'){
for (var i = 0,x = array.length;i<x;i++){
var obj = array[i];
var match = true;
for (var j in properties){
if (obj[j] !== properties[j]){
match = false;
}
}
if (match) {returnArray.push(i)};
}
}
return returnArray;
}
The above function not returning any value. I would like it to returning array like this which contain size value following by stock value [{36,10}, {37,16}, {38,13}, {39,17}, {40,12}]
As you can see each returned value have a matching id.
Any help is much appreciated.
Flow:
Create a hashtable of id:stock
Use Array.map to retrieve stock from hash table using id of arraysize
Snippet:
var arraysize = [{ id: 59, size: 36}, { id: 123, size: 37}, { id: 62, size: 38}, { id: 63, size: 39}, { id: 64, size: 40}];
var arraycode = [{ id: 63, stock: 17}, { id: 123, stock: 16}, { id: 59, stock: 10}, { id: 64, stock: 12}, { id: 62, stock: 13}];
var arrayCodeObj = {};
arraycode.forEach(function(obj){arrayCodeObj[obj.id]=obj.stock});//create hash table
var arr2d = arraysize.map(function(obj){ return [obj.size, arrayCodeObj[obj.id]]})
console.log(arr2d)
console.log(arrayCodeObj)
I am trying to get the first value, in other words each of the objects.name to be printed/logged.
In this example, I would like Tom, Tom, Fox
var tom = {
name: "Tom",
age: 23,
location: "London"
};
var tom2 = {
name: "Tom",
age: 21,
location: "London"
};
var fox = {
name: "Fox",
age: 23,
location: "London"
};
var arr = [tom, tom2, fox];
for (var i = 0; i < arr.length; i++) {
var objectArr = arr[i]
for (var prop in objectArr) {
var values = objectArr[prop];
console.log(values)
}
}
You can simply use forEach built-in array function. Array.forEach():
arr.forEach(function (arrayItem) {
var x = arrayItem.name;
console.log(x);
});
One short way would be:
var arr = [tom, tom2, fox];
console.log(arr.map(el => el.name));
Using the function map on Array to get an array with only the object field you want and then the console.log function can take an array for argument and print it.
Please refer the following code:
import UIKit
struct Item {
var brandId = 1
var name: String = ""
}
struct Store {
var areaName = ""
var name: String = ""
}
let itemArray = [Item(brandId: 1, name: "item1"), Item(brandId: 2, name: "item2"), Item(brandId: 1, name: "item3") ]
let storeArray = [Store(areaName: "hk", name: "store1"), Store(areaName: "bj", name: "store2"), Store(areaName: "hk", name: "store3")]
var intKeys = [Int]()
var groupedItems = [[Item]]()
var stringKeys = [String]()
var groupedStores = [[Store]]()
extension Array {
func transTo2d() -> [[Element]] {
let grouped = [[Element]]()
return grouped
}
}
itemArray.forEach { (item) in
let brandId = item.brandId
if !intKeys.contains(brandId) {
intKeys.append(brandId)
var newArray = [Item]()
newArray.append(item)
groupedItems.append(newArray)
} else {
let index = intKeys.index(of: brandId)!
groupedItems[index].append(item)
}
}
My final goal is could using itemArray.transTo2d() get a 2d array based on item's brandId, using storeArray.transTo2d() get a 2d array based on store's areaName. I don't how to generic the function that trans 1d array to a 2d array based on the key?
I don't think you can write a generic extension for an Array where the elements will either be of type Item or Store since both of them don't share any relation for you to write a common generic method. You can write extensions for Array where the elements will be of the mentioned type. You just need to conform both of your structs to the equatable protocol.
struct Item {
var brandId = 1
var name: String = ""
}
extension Item : Equatable{
static func ==(lhs: Item, rhs: Item) -> Bool{
return lhs.brandId == rhs.brandId
}
}
struct Store {
var areaName = ""
var name: String = ""
}
extension Store : Equatable{
static func ==(lhs: Store, rhs: Store) -> Bool{
return lhs.areaName == rhs.areaName
}
}
extension Array where Element == Store{
func transform()->[[Store]]{
var storeArray = self
var groupedArray = [[Store]]()
while storeArray.count > 0{
if let firstElement = storeArray.first{
groupedArray.append(storeArray.filter{$0.areaName == firstElement.areaName})
storeArray = storeArray.filter{$0.areaName != firstElement.areaName}
}
}
return groupedArray
}
}
extension Array where Element == Item{
func transform()->[[Item]]{
var itemArray = self
var groupedArray = [[Item]]()
while itemArray.count > 0{
if let firstElement = itemArray.first{
groupedArray.append(itemArray.filter{$0.brandId == firstElement.brandId})
itemArray = itemArray.filter{$0.brandId != firstElement.brandId}
}
}
return groupedArray
}
}
Using the transform function
let storeArray = [Store(areaName: "hk", name: "store1"), Store(areaName: "bj", name: "store2"), Store(areaName: "hk", name: "store3")]
let itemArray = [Item(brandId: 1, name: "item1"), Item(brandId: 2, name: "item2"), Item(brandId: 1, name: "item3") ]
print(storeArray.transform())
print(itemArray.transform())
This will print this output which is what I believe you wanted.
[[Store(areaName: "hk", name: "store1"), Store(areaName: "hk", name: "store3")], [Store(areaName: "bj", name: "store2")]]
[[Item(brandId: 1, name: "item1"), Item(brandId: 1, name: "item3")], [Item(brandId: 2, name: "item2")]]
I got an array from database as
[
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
Now my required answer is that should be in the following format,
[["abc",100],
["xyz",150]]
But after some coding I got an array of Array as shown below in the console
[0:[0:"abc",1:100]
1:[0:"xyz",1:150]]
Before question down / marking duplicate please read my requirement, and if its there then mark it and please post that link as per my required solution so i can get my solution from there
So any help will be great help....
You can do like this:
data = [
{id:
{unitno: 'abc'},
amount: 100},
{id:
{unitno: 'xyz'},
amount: 150}
]
var array =[]
data.forEach(function(item){
var tmpArray = []
tmpArray.push(item.id.unitno,item.amount)
array.push(tmpArray)
})
Now you will get your required data in the array.
I don't know how you got this below code, but that's invalid Array
[0:[0:"abc",1:100] 1:[0:"xyz",1:150]]
For your desired output you can do it with JavaScript, no need angular. Just run a simple for loop.
var temp1 = [{
id: {
unitno: 'abc'
},
amount: 100
}, {
id: {
unitno: 'xyz'
},
amount: 150
}];
var eee = [];
temp1.forEach(function(el) {
eee.push([el.id.unitno, el.amount])
});
console.log('eee:', eee);
Hope this is what you needed.
var arr = [{
id : { unitno: 'abc' },
amount: 100
},{
id : { unitno: 'xyz' },
amount: 150
}];
var result = [];
for (var i = 0; i < arr.length; i++) {
var newArray = [];
newArray.push( arr[i]["id"]["unitno"] );
newArray.push( arr[i]["amount"] );
result.push( newArray );
}
console.log( result );
I want to create a new nested array with the name of a variable. Is this possible?
data example:
[{
varname {
name: person1name;
events : [{
firstName: person1name,
name: event1name,
date: date1
},{
firstName: person2name,
name: event2name,
date: date2
}
]
}
}]
code:
$scope.multiEvents = []
var eventCategory = $scope.event.name
$scope.multiEvents.eventCategory.name = $scope.event.firstName;
$scope.multiEvents.eventCategory.events.push($scope.event);
$scope.multiEvents.eventCategory.events.push($scope.event2);
Ended up doing this:
$scope.multiEvents = [];
$scope.multiEvent = {};
$scope.multiEvent.events = [];
$scope.multiEvent.name = $scope.event.firstName;
$scope.multiEvent.events.push($scope.event);
$scope.multiEvent.events.push($scope.event2);
$scope.multiEvents.push($scope.multiEvent);
I think I was just confused.