I have a case like, I want to add elements into a JSON array in TypeScript like below
[
{
"a" : "a1",
"b" : "b1"
}
]
Now I want to add values to the above object without creating new block, for example, I want to add key, value pair as "C": "c1" and "d": "d1". After doing this, my JSON array must look like below
[
{
"a" : "a1",
"b" : "b1"
"c" : "c1",
"d" : "d1"
}
]
What I tried:
let someData : any [] = [];
someData.push({
"a" : "a1",
"b" : b1"
})
someData.push({
"c" : "c1",
"d" : d1"
})
But it is creating two records like below, but this is wrong
[
{
"a" : "a1",
"b" : "b1"
}
{
"c" : "c1",
"d" : "d1"
}
]
as well I tried using unshift as below
someData.unshift({
"c" : "c1",
"d" : d1"
})
this is returning result object as
[
{
"a" : "a1",
"b" : "b1"
}
{
"c" : "c1",
"d" : "d1"
}
]
Is there any way to do?
For example,
for(int i =0; i<3; i++){
someData.push({
i : i+1
})
But the above block of code is creating wrong array structure, but inturn I want as below
{
0 :1,
1:2,
2:3
}
}
Its supposed to be like this...
let someData : any [] = [];
someData.push({
"a" : "a1",
"b" : b1"
})
someData[0]["c"] = "c1";
someData[0]["d"] = "d1";
So when you log the values of someData ... it will show
console.log(someData); //[{"a":"a1","b" : "b1", "c":"c1", "d":"d1"}]
for looping through values...
let valuesToPut = [["c","c1"],["d","d1"]];
for(let i = 0; i < valuesToPut.length; i++){
someData[0][valuesToPut[i][0]] = valuesToPut[i][1]
}
is little confusion between Object and Array, here you try to add some item to the Object who are store on index 0 of your array.
let try following code :
let someData : any [] = [];
// Create first index of array and create on it your Object.
someData.push({
"a" : "a1",
"b" : b1"
});
// Override first index of array by merge of previous data + new one.
someData[0] = Object.assign(someData[0], {
"c1" : "c1",
"d1" : "d1"
});
Object assign documentation
Another way to do this: Object.defineProperties()
As you mensioned, it is an array json format.
So, if you access some element in the array, you should indicate the array index.
ex:
let tempArray = [
{
"a" : "a1",
"b" : "b1"
}
]
=>
tempArray[0] has this value.
{
"a" : "a1",
"b" : "b1"
}
So, if you add some additional values to the tempArray[0], you should access the element like below :
tempArray[0]['c'] = "c1";
tempArray[0]['d'] = "d1";
//Let's start with what you're doing
let someData = [];
someData.push({
"a" : "a1",
"b" : "b1"
});
// pushes a collection of 2 key value pairs in as the first entry to someData
someData.push({
"c" : "c1",
"d" : "d1"
});
// pushes a collection of 2 key value pairs in as the second entry to someData
console.log(someData);
// what you might want to do:
someData = [];
someData.push({
"a" : "a1",
"b" : "b1"
});
// pushes a collection of 2 key value pairs in as the first entry to someData
someData[0].c = "c1";
//Sets a value to the key c in the first element of some data
someData[0].d = "d1";
//Sets a value to the key d in the first element of some data
console.log(someData)
// What you probably want to do.
someData = {};
for(let i of [1,2,3,4]){
someData[String.fromCharCode(i+96)] = String.fromCharCode(i+96)+"1";
}
console.log(someData)
Related
let's suppose we have this variable:
foobars = {
"first" : {
specialkeys: [
"a",
"b",
"c"
]
}
"second" : {}
}
now let's say we would like to loop over that foobars object knowing that specialkeys doesn't exist in the "second" object.
This is what I tried but it complains that
This object does not have an attribute named specialkeys
My tries:
data = flatten([
for k, v in var.foobars : [
for sk in v.specialkeys : {
special = sk,
foo = k
}
]
])
I believe you would want to do the following:
data = flatten([
for k, v in local.foobars :
[
for sk, sv in v :
[
for spec in sv : {
special = spec,
foo = k
}
]
]
])
This will output something like this:
[
{
"foo" = "first"
"special" = "a"
},
{
"foo" = "first"
"special" = "b"
},
{
"foo" = "first"
"special" = "c"
},
]
I am trying to make an array of random numbers for an ID for 25 people so I figured that would be the easiest way would use a array map but is there a way to take each element and attach it to an "email" in the dictionary key.
class ClassRosterModel {
var randomArray = (1...25).map{_ in arc4random()}
var studentsRoster = [Dictionary<String, String>] ()
init () {
studentsRoster.append(["name": "Kacz, Alex", "major" : "SE", "email" : ".join(randomArray[0])#email.edu", "currentTerm" : "Spring", "numberOfCredits" : "" ])
studentsRoster.append(["name": "O'Rore, Ryan", "major" : "SE", "email" : ".join(randomArray[0]#email.edu", "currentTerm" : "Fall", "numberOfCredits" : "" ])
}
}
From what I am understanding, you want to put a value inside a string. You can use \().
Example:
let value = 101
let email = "myname\(value)#email.com"
print(email)
The console result will be:
myname101#email.com
Just use your randomArray instead of value. And save the email inside your dictionary.
studentsRoster.append(["name": "Kacz, Alex", "major" : "SE", "email" : ".join\(randomArray[0])#email.edu", "currentTerm" : "Spring", "numberOfCredits" : "" ])
studentsRoster.append(["name": "O'Rore, Ryan", "major" : "SE", "email" : ".join\(randomArray[0])#email.edu", "currentTerm" : "Fall", "numberOfCredits" : "" ])
I have a dictionary, which looks like this:
var dict = [["number" : "1" ], ["number" : "2" ], ["number" : "3" ]]
Now I would like to add new value "level" : "(number of level)" to each index in my dictionary, and it should looks like that:
var dict = [["number" : "1", "level" : "one"], ["number" : "2", "level" : "two" ], ["number" : "3", "level" : "three" ]]
How can I add some value inside existing dictionary in this case?
What you have listed as a dictionary is actually an array of dictionaries. You can add an element to each of the directories by simply iterating the array.
You can use an NSNumberFormatter to convert the digits you have into equivalent words:
var anArray=[["number":"1"],["number":"2"],["number":"3"]]
let numberFormatter=NSNumberFormatter()
numberFormatter.numberStyle=NSNumberFormatterStyle.SpellOutStyle
for i in 0..<anArray.count {
if let numberString=anArray[i]["number"] {
if let number=Int(numberString) {
anArray[i]["level"]=numberFormatter.stringFromNumber(number)
}
}
}
As Paulw11 pointed out, you could use NSNumberFormatter to convert the digits to words:
let dictArray = [["number" : "1" ], ["number" : "2" ], ["number" : "3" ]]
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
let mappedDictArray = dictArray.map { var d = $0; d["level"] = numberFormatter.stringFromNumber(number); return d; }
However, if you're interested in using the level key only for UI purposes, you'd be better writing a Dictionary extension, as there's no point is storing a redundant value:
extension Dictionary {
func levelString() -> String {
let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.SpellOutStyle
return numberFormatter.stringFromNumber(self["number"] as? Int ?? 0)
}
}
which can be used like this:
dictArray[0].level()
instead of an array:
var arrayExample = {
"lotsOfStuff" : [
{"id" : "th1", "name" : "thing1", "type": "thing", "moo":"a"},
{"id" : "th2", "name" : "thing2", "type": "thing", "moo":"z"},
{"id" : "th3", "name" : "aDifferentThing3", "type": "differentThing", "moo":"m"}
]
}
Use lots of properties:
var propertyExample = {
"lotsOfStuff" : {
"id1" : {"name" : "thing1", "type" : "thing", "moo" : "a" },
"id2" : {"name" : "thing2", "type" : "thing", "moo" : "z" },
"id3" : {"name" : "aDifferentThing3", "type" : "differentThing", "moo" : "m" }
}
}
can still iterate through them
for(var idx in arrayExample.lotsOfStuff) {
var thing = lotsOfStuff[idx];
var id = thing.id;
...
}
and
for(var id in propertyExample) {
var thing = lotsOfStuff[id];
...
}
but you have the bonus of a lookup by id at the expense of the lookup by index position
Any problems with using this array alternative??
what about performance with lots of elements??
If the order of the elements matters, use an array.
If you need to look up by ID, use an object.
If you need to do both, create both an array and an object whose elements point to the same objects.
Accessing object properties is probably slower than accessing array elements, because it requires hashing instead of simple indexing. But if you need to look up by ID in an array, that will require a linear search, which is much slower than hashing if there are lots of elements. The performance of objects should not be impacted significantly by the number of elements.
I am trying to extract data from an array in a collection, the extract of code is shown below:
> db.nodes.findOne()
{
"_id" : NumberLong(24060429),
"_t" : "OsmNode",
"uname" : "studerap",
"uid" : 7260,
"version" : 2,
"changeset" : 634057,
"timestamp" : ISODate("2007-11-27T11:18:58Z"),
"tags" : [
[
"created_by",
"almien_coastlines"
],
[
"source",
"PGS"
]
],
"tagKeys" : [
"created_by",
"source"
],
"location" : [
5.5442938804626465,
-6.488432884216309
]
}
The data i actually want to retrieve is 5.5442938804626465 from the location array. Shall it be retrieved through index?
Thanks for helping
To extract that indexed element of array from all documents, you can get through:
var index = 0, count = 1;
var cursor = db.nodes.find({}, {_id:1, location:{$slice:[index, count]}});
Of course, you can write directly:
var cursor = db.nodes.find({}, {_id:1, location:{$slice:[0, 1]}});
Or
var cursor = db.nodes.find({}, {_id:1, location:{$slice:1}});
Then, extract the result:
var results = [];
cursor.forEach(function(e) {
results.push(e.location[0]);
});
By the way, .find() returns a cursor; and .findOne() returns a document, which is equivalent to running .find().next() once if cursor has documents.