How to get only the first value/property of each object - arrays

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.

Related

javascript Can I make an array of object?

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

Matching two array key and combine it's value with google app script

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)

How to Create Optional Struct with Arrays

I would like to create the following struct/array combination; however, I'm getting lost in the array nesting. Is this the proper way to set up a "City", and if so, what would be the best practice technique to modify it, so that I can init new Cities with a different customer value?
Thanks!
struct City {
var name: String
var groceryStores: [GroceryStore]
}
struct GroceryStore {
var name: String
var employeesAtInterval = [employeeIDs]
}
var employeeIDs = [40, 20, 13, 44]
Based on your code, this seems like what you wanted to achieve:
struct City {
var name: String
var groceryStores: [GroceryStore]
}
struct GroceryStore {
var name: String
// As employeeIDs are Ints, you should initialize it using this syntax
var employeesAtInterval = [Int]()
}
let employeeIDs1 = [40, 20, 13, 44]
let employeeIDs2 = [40, 20, 13, 44]
...
let groceryStore1 = GroceryStore(
name: "store 1",
employeesAtInterval: employeeIDs1
)
let groceryStore2 = GroceryStore(
name: "store 2",
employeesAtInterval: employeeIDs2
)
...
let city1 = City(name: "city 1", groceryStores: [groceryStore1, groceryStore2])
let city2 = City(name: "city 2", groceryStores: [groceryStore3, groceryStore4])
let cities = [city1, city2]

How to generic a function where params are different structs with different properties?

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")]]

How to mutate Values inside a Array

I need to mutate the following array:
struct Person {
var name: String
var age = 0
}
func showPersonArray() -> [Person] {
var dataArray = [Person]()
dataArray.append(Person(name: "Sarah_Yayvo", age: 29))
dataArray.append(Person(name: "Shanda_Lear", age: 45))
dataArray.append(Person(name: "Heidi_Clare", age: 45))
return dataArray
}
How could I split the "name"-key into two keys: "givenName" and "familyName".
Some nice person gave me this code before:
let arraySeparated1 = dataArray.map { $0.substring(to: $0.range(of: "_")!.lowerBound) }
let arraySeparated2 = dataArray.map { $0.substring(from: $0.range(of: "_")!.upperBound) }
Is it possible to make the mutation inside the struct?
The function showPersonArray() is only for demo and test.
Maybe there is a way to work with a target struct, like this:
struct Persontarget {
var familyname: String
var givenName: String
var age = 0
}
struct Person: Array -> [Persontarget] {
var name: String
var age = 0
// Here the split/mutating code
return [PersonWithTwoNames]
}
Or with an String extension. Possibly my question sounds pretty newby-like, but i´m trying the whole day...
Thanks everyone!
I would write an initializer on the new Person type, which initializes it from the old person type (which I called LegacyPerson):
import Foundation
struct LegacyPerson {
let name: String
let age: Int
}
func getPersonArray() -> [LegacyPerson] {
return [
LegacyPerson(name: "Sarah_Yayvo", age: 29),
LegacyPerson(name: "Shanda_Lear", age: 45),
LegacyPerson(name: "Heidi_Clare", age: 45)
]
}
struct Person {
let familyName: String
let givenName: String
let age: Int
}
extension Person {
init(fromLegacyPerson person: LegacyPerson) {
let index = person.name.range(of: "_")!
self.init(
familyName: person.name.substring(from: index.upperBound),
givenName: person.name.substring(to: index.lowerBound),
age: person.age
)
}
}
let people: [Person] = getPersonArray().map(Person.init)
people.forEach{ print($0) }
Create a method or computer variable for your Person class that returns what you want.
func firstName() -> String {
return self.substring(to: $0.range(of: "_")!.lowerBound)
}
You should not force cast though
with help of computed property defined in an extension
struct Person {
let name: String
let age: Int
}
let person = Person(name: "Maria_Terezia", age: 300)
extension Person {
var names:[String] {
get {
return name.characters.split(separator: "_").map(String.init)
}
}
}
for name in person.names {
print(name)
}
prints
Maria
Terezia

Resources