Angular JS : using dynamic object names from list of Objects - angularjs

Is there any way to read an object from a list of objects dynamically with object key.
My complex objects is something like :
$scope.mainObject = {
name : "Some value",
desc : "Some desc",
key1: {
arrayLst: []
},
key2: {
arrayLst: []
}
}
In my method, I have the key value either key1 or key2 in a string keyValue. How can I write to object like :
$scope.mainObject.key1.arrayLst = data;
In the form of something like :
$scope.mainObject.get(keyValue).arrayLst = data;

Well, there's something known as Array notation in JavaScript objects. More on it here.
You can write it something like this :
$scope.mainObject.[keyValue].arrayLst = data;

Related

How to convert a list of key-value pairs into list of objects in TypeScript?

I need a "quick and easy" way of converting this:
var raw =
[
[{"key":"key1v", "value":"value1v"},{"key":"key2v", "value":"value2v"}],
[{"key":"key3v", "value":"value3v"},{"key":"key4v", "value":"value4v"}]
]
into something like this:
var data =
[
{key1v:"value1v",key2v:"value2v"},
{key3v:"value3v",key4v:"value4v"}
]
so in the raw data, the key and value are always named "key" and "value"
in the output data the value of the "key" have to be the key itself and as value the value of the "value key"
i hope it doesn´t sound to confusing..
As I understand you need something like this?
raw.map(line => {
return line.reduce((acc, item) => {
acc[item.key] = item.value
return acc
}, {})
})

Typescript: Strongly type incoming array with variable types

I have a JSON array which can contain either of two types defined by IPerson and ICompany.
[
{ "Name" : "Bob", "Age" : 50, "Address": "New Jersey"},
{ "Name" : "ABC Inc", "Founded" : 1970, "CEO": "Alice" }
]
This data is received from an endpoint. I want to map this data exactly in same way in my client application in Typescript. How should I define my model in this case.
I know we can define same interfaces in TypeScript but is it possible to have an array that holds either of two objects defined by IPerson and ICompany and know the type of each item while iterating the array?
You can have an Array<IPerson | ICompany>. For iterating, you can do something like this
function iterateMyArray(array: Array<IPerson | ICompany>) {
array.forEach(item => {
if ('Age' in item) {
// item is an person
console.log(item.Address);
} else {
// item is a company
}
})
}

Why isn't as3 handing my arrays in JSON?

Here I have this json file.
{
"BnUs5hQZkJWLU9jGlpx9Ifq5ocf2" : {
"bio" : "Your bio!\r",
"birthday" : "Date of Birth?",
"location" : "Location?",
"markerBorder" : 1.5542403222038021E7,
"markerColor" : 8222122.31461079,
"name" : "NamesName?",
"profilePrivacy" : 2,
"sex" : "Gender?",
"privacy" : 2,
"points" : {
"-Kc7lfJk3XbPlNyk-wIR" : {
"address" : "dsfsdfasfsfd",
"description" : "status/desription",
"latitude" : 35.2,
"longitude" : -80.7,
"mediaTargets" : "none",
"pub" : false,
"timestamp" : 1486205926658
},
"aaa" : "aaa"
}
}
}
Those random string of charactors are automatically made when I use firebase.
In this scenario, there might be more "points" I will have to take account for. So when I reference points, I should be talking to an array since it contains both "-Kc7lfJk3XbPlNyk-wIR" (an array) and "aaa" (a string).
So why do I get a type error when trying to convert parsedObject.points into an array?
var parsedObject:Object = JSON.parse(e.target.data);
var multiArray:Array = parsedObject.points;
TypeError: Error #1034: Type Coercion failed: cannot convert Object#5c16089 to Array.
I'm basically trying to do the opposite of what this guy is doing.
Edit: I see in the notes that it only handles string, numbers and Boolean values..
I managed to work around it by adding a "parent" node in the object that duplicates the same value as the name of the entire node so I can reference it in the script. Is there a better way to go about this? Seems pretty redundant.
var parsedObject:Object = JSON.parse(e.target.data);
var myPoints:Object = parsedObject["points"];
//Get all trek names
for each (var key:Object in myPoints)
{
trace("Key = " + key.parent);
trace(parsedObject.treks[key.parent].latitude) //Returns -80.7
}
Because Array is a subclass of Object.
var A:Array = new Array();
var B:Object = new Object();
trace(A is Array); // true
trace(A is Object); // true
trace(B is Array); // false
trace(B is Object); // true
B = new Array(); // nothing wrong here
A = new Object(); // throws exception
So, you might want to tell what kind of data you want to obtain in the Array form from the parsedObject.points Object to proceed.
Alternately, that is how you get actual Array from JSON string:
{
"list": [1,2,3,4,5,6]
}
Looks like it's correctly being parsed by JSON.parse to me.
Arrays in JSON use square brackets, braces are interpreted as objects.
You'd only expect an Array from JSON.parse if you had
"points": [
...
]
whereas this is an Object:
"points": {
...
}
I suggest you look into why you aren't getting [] from your source.

How to validate empty array of strings with ajv?

I make json validation with ajv. I need to validate array of strings. I know which elements can be placed there so I make appropriate 'enum'. But in some case enum can be empty and array can be empty too. Here is simple test:
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : []
}
}
var data = [];
var Ajv = require('./ajv-4.1.1.js');
var ajv = Ajv({
allErrors : true
});
var validate = ajv.compile(schema);
var valid = validate(data);
if (!valid)
console.log(validate.errors);
As a result I get:
Error: schema is invalid:data.items.enum should NOT have less than 1 items, data.items should be array, data.items should match some schema in anyOf
I can add any fictive string to enum array but is it possible to validate this case in legal way? Adding 'minItems=0' restriction doesn't help.
Is it really json schema draft restriction that I can't use empty enum?
UPD: I expect to validate code in general case:
var array = Object.keys(someObj); // array: ["foo", "bar"]
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = ["foo"]; // valid
var data = ["bar"]; // valid
var data = ["bar","foo"]; // valid
I expect to validate code in special case:
var array = Object.keys(someObj); // array: []
var schema = {
"type":"array",
"items" : {
"type" : "string",
"enum" : array
}
}
var data = []; // I expect to see it valid too but get error instead.
The enum keyword is required to have at least one value. The specification states ...
5.5.1.1. Valid values
The value of this keyword MUST be an array. This array MUST have at least one element. Elements in the array MUST be unique.
Elements in the array MAY be of any type, including null.
http://json-schema.org/latest/json-schema-validation.html#anchor76
This makes sense because an empty enum would mean nothing would ever validate. However, I do see how it could come in handy in your particular case. If you need to build the schema dynamically, you will need to check for the empty array case and use a different schema.
Here's one way to do it:
{
"type": "array",
"maxItems": 0
}
Here's another:
{
"type": "array",
"not": {}
}

How to filter object from array by value and using the value to omit another array or objects?

I have a array, which has the bunch of object, i would like to filter the object by 'name' value, again i would like to omit those object from another array of object using underscore.
I know that we can do using earch, but i am not getting the proper approach to do this both..
any one help me to do this?
example :
incoming array:
var incomingArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
];
filter keys:
var omit = ['orange' ,'dog'];
//i need to check whether 'orange' or 'dog' are exist, if so..
var filtered = _.filter(incomingArray, function(obj, i){
return obj.name === omit[i]['name'];//this is wrong i need to loop again how?
});
var anotherArray = [
{"name":"apple"},
{"name":"orange"},
{"name":"dog"},
{"name":"cat"},
{"name":"egle"}
]
return only the array without the omit like this:
var outgoingArray = [
{"name":"apple"},
{"name":"cat"},
{"name":"egle"} ]
how we could achieve this with proper approach?
demo
You were nearly there! Use indexOf to check that the name does not belong in the omit array:
var filtered = _.filter(incomingArray, function(obj) {
return omit.indexOf(obj.name) == -1;
});

Resources