Populate an array of array of objects - arrays

I must populate an array of array of objects to get something like this:
let dataObj = [
[
{ content: "test1"},
{ content: "test2"},
{ content: "test3"}
],
[
{ content: "test4"},
{ content: "test5"},
{ content: "test6"}
]
]
I start from an array of arrays like this:
data = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]
I tried with:
let dataObj = <any>[[{ }]];
for (let i = 0; i < data.length; i++) {
for (let j=0; j < data[i].length; j++) {
dataObj[i][j].content = data[i][j];
}
}
but after populating the first ([0][0]) it stops and the error is an
uncaught in promise...
(I work in Angular-TypeScript)
I tried also with:
dataObj.push(i,j,{content: data[i][j]});
It gets a result but it's completely wrong.

Add an array into the root array.
Add an object into the nested array.
let dataObj: { content: any;[key: string]: any }[][] = [];
for (let i = 0; i < data.length; i++) {
dataObj.push([]);
for (let j = 0; j < data[i].length; j++) {
dataObj[i].push({ content: data[i][j] })
}
}
Alternatively, you can work with .map().
let dataObj: { content: any;[key: string]: any }[][] = [];
dataObj = data.map(x =>
x.map(y => {
return { content: y };
})
);
Sample TypeScript Playground

Related

Combine arrays and add flag to it if matches the ID

I have two arrays that are identical in structure.
let TaskArray=[
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
let TaskDetailsArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3"},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3"},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3"},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3"},
]
I need to compare the two arrays and set the flag isAssigned to true if an item from the second array is found by id in the first array, and false otherwise.
matcheArray = [
{"TaskID:"171","TaskName":"task1","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"170","TaskName":"task2","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"169","TaskName":"task3","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"168","TaskName":"task4","TaskGroup":"group","UserID":"3",isAssigned: true},
{"TaskID:"167","TaskName":"task5","TaskGroup":"group","UserID":"3"},
{"TaskID:"166","TaskName":"task6","TaskGroup":"group","UserID":"3"},
{"TaskID:"165","TaskName":"task7","TaskGroup":"group","UserID":"3"},
{"TaskID:"164","TaskName":"task8","TaskGroup":"group","UserID":"3"},
{"TaskID:"163","TaskName":"task9","TaskGroup":"group","UserID":"3"},
{"TaskID:"162","TaskName":"task10","TaskGroup":"group","UserID":"3"}
]
The code below works ok, but I'm not sure whether there is a better way to accomplish it. Please suggest.
for (var i = 0; i < TaskArray.length; i++) {
for (var k = 0; k < this.TaskDetailsArray.length; k++) {
if (TaskArray[i].TaskID == this.TaskDetailsArray[k].TaskID) {
if (!this.TaskDetailsArray[k].isAssigned) {
this.TaskDetailsArray[k].isAssigned = true;
};
}
}
const comparedArray = taskArray.map(item => {
return {
...item,
isAssigned: TaskDetailsArray.some(secondItem => secondItem.TaskId === item.TaskId );
}
})

Creating and pushing elements in an new array depends on conditions

My Data Array
data:[
0:{
id:1 ,.....
competetion:[
0:{
id: 1....,
match:[
0:{id: 1 ......},
1:{same}
.
.
]
1:{same}]},
2:{same}
.
.
]
},
1:{same},
2:{same}
.
.
.
]
For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...
My Code: Here i am looping it:
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
this.sportarr.push({ // I declared a new array where i want to push the element
id: i,
value: false
});
}
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map
const arrlength = data.length;
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = data[i].competetion.map( (val, index) => {
#write your own logic to produce the required outcome
return {
id: index,
value: false
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
i Appriciate Pathikrit Sanyal and Fahd Lihidheb For the ansers
Here Is my Change according to Pathikrit Sanyal
for (let i = 0; i < arrlength; i++) {
let competition = [];
competition = response.data[i].competetion.map((val, index) => {
let match = [];
match = val.match.map((value, indx) => {
return {
id: indx,
value: false
};
});
return {
id: index,
value: false,
match
};
});
this.sportarr.push({
id: i,
value: false,
competetion: competition
});
console.log('myarrr...', this.sportarr);
}
Now i am getting what i wanted
i am not sure if you are trying to create an array for each nasted array (competetion and match) or not, but here you go
this.sportsSidebar = response.data; // My data Array (this.sportsSidebar)
const competetionList = // Array of competetions
[].concat.apply([], this.sportsSidebar.map(item => item.competetion));
const matchList = // Array of matchs
[].concat.apply([], competetionList .map(item => item.match));
}

JSON parsing multiple nested arrays

I am trying to parse below json, which has multiple nested lists (input & output), how do I parse it ?
{
"status":"current",
"entry":[{
"item":{
"name":"Task1",
"identifier":"T00001",
"input":[{
"type":{
"text":"InputTask1-1"
},
"valueString":"Weekly"
},
{
"type":{
"text":"InputTask1-2"
},
"valueString":"Daily"
}
],
"output":[{
"type":{
"text":"OutputTask1-1"
},
"valueString":"Daily"
},
{
"type":{
"text":"OutputTask1-2"
},
"valueString":"Weekly"
}
]
}
},
{
"item":{
"name":"Task2",
"identifier":"T00002",
"input":[{
"type":{
"text":"InputTask2-1"
},
"valueString":"Weekly"
},
{
"type":{
"text":"InputTask2-2"
},
"valueString":"Daily"
}
],
"output":[{
"type":{
"text":"OutputTask2-1"
},
"valueString":"Daily"
},
{
"type":{
"text":"OutputTask2-2"
},
"valueString":"Weekly"
}
]
}
}
]
}
Looking for delimited output file like this:
"TaskName"|"TaskId"|"InputName"|"InputValue"|"OutputName"|"OutputValue"
Task1|T00001|InputTask1-1|Weekly|outputDummyText|outputDummyValue
Task1|T00001|InputTask1-2|Daily|outputDummyText|outputDummyValue
Task1|T00001|inputDummyText|inputDummyValue|OutputTask1-1|Daily
Task1|T00001|inputDummyText|inputDummyValue|OutputTask1-2|Weekly
Task2|T00002|InputTask2-1|Weekly|outputDummyText|outputDummyValue
Task2|T00002|InputTask2-2|Daily|outputDummyText|outputDummyValue
Task2|T00002|inputDummyText|inputDummyValue|OutputTask2-1|Daily
Task2|T00002|inputDummyText|inputDummyValue|OutputTask2-2|Weekly
Use Kotlin and Gson library.
Define your model:
data class MyData(val status: String, val entry: List<Entry.ItemContainer>) {
data class Entry(val itemContainer: List<ItemContainer>) {
data class ItemContainer(val item: Item) {
data class Item(
val name: String,
val identifier: String,
val input: List<TypeContainer>,
val output: List<TypeContainer>
) {
data class TypeContainer(val valueString: String, val type: Type) {
data class Type(val text: String)
}
}
}
}
}
Read json string from file:
val json = File("data.json").readText()
Map the data to the defined model using Gson:
val myData = Gson().fromJson<MyData>(json, MyData::class.java)
Print the result in desired format (or save it to file):
println("\"TaskName\"|\"TaskId\"|\"InputName\"|\"InputValue\"|\"OutputName\"|\"OutputValue\"")
for (itemContainer: MyData.Entry.ItemContainer in myData.entry) {
with(itemContainer.item) {
for (typeContainer in input) {
println("$name|$identifier|${typeContainer.type.text}|${typeContainer.valueString}|outputDummyText|outputDummyValue")
}
for (typeContainer in output) {
println("$name|$identifier|inputDummyText|inputDummyValue|${typeContainer.type.text}|${typeContainer.valueString}")
}
}
}
Try this
JSONObject jsonParent = new JSONObject(response);
JSONArray jsonarray = jsonParent .getJSONArray("entry");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject c = jsonarray.getJSONObject(i);
JSONObject jsonItem = c.getString("item");
JSONArray inputItemArray = jsonItem.getJSONArray("input");
for (int j = 0; j < inputItemArray.length(); j++) {
JSONObject inputItemObj = inputItemArray .getJSONObject(j);
String invalueString = inputItemObj.getSting("valueString ");
}
JSONArray outputItemArray = jsonItem.getJSONArray("output");
for (int k = 0; k < outputItemArray.length(); k++) {
JSONObject outputItemObj = outputItemArray.getJSONObject(K);
String outvalueString = outputItemObj.getSting("valueString ");
}
}

Can't get array data of Mongoose/MongoDB

var productSchema = mongoose.Schema({
user_id:String,
products:[]
});
var Products = mongoose.model('Products', productSchema);
...
...
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
var f = docs[i].products;
console.log(f);
});
Finally I can consoled this
{ _id: 8017ced8gf73kk25a8d9839x,
user_id: '739265b0dlskca14d8djd1a1',
__v: 0,
products:
[ { color: 'yellow', name: 'A' },
{ name: 'B', color: 'red' } ] }
But what I want is 'yellow' in Array!! not Array data.
I need to access the data in {}.
var f = docs[i].products.color;
And I tried this but it makes error.
If you want it in javascript you can run a loop through inner products array
Products.find({},function(err,docs){
for(var i = 0; i < docs.length; i++){
for(var j in docs[i].products){
if(docs[i].products[j] && docs[i].products[j].color){
console.log(docs[i].products[j].color)
}
}
});

Angular2 JSON Duplication Deletion

I am working with a large JSON file holding information about instructors at my school. I want to be able to pull all the teachers names from this list so I can then put them into Firebase. However, whenever I loop over my JSON file and try to filter out all the duplicate teacher names I still end up with duplicates even when I try to do a second round of deletion. The JSON looks like this:
{
"Id": "1",
…
"Instructor": "name1, name2, name3",
…
},
{
"Id": "2",
…
"Instructor": "name1",
…
},
{
"Id": "3",
…
"Instructor": "name1, name2",
…
}
As seen above sometimes there is just one name, other times there are multiple. I handle this though in my logic but no matter what I still end up with duplicates. If anyone can help me come up with a way to solve this it would be greatly appreciated. I'll add my code that I have already below.
public remove_duplicates(arr: any[]): any[] {
let output: any[] = [];
for (let i = 0; i < arr.length; i++) {
let instruc: any[] = arr[i].Instructor.split(',');
for (let j = 0; j < instruc.length; j++) {
let push: boolean = true;
arr[i].Instructor = instruc[j];
for (let k = 0; k < output.length; k++) {
let i1: string = output[k].Instructor;
let i2: string = arr[i].Instructor;
if (i1.trim().localeCompare(i2.trim()) == 0) {
push = false;
}
}
if (push)
output.push(arr[i]);
}
}
console.log(output.length);
for (let k = 0; k < output.length; k++) {
for (let i = k + 1; i < output.length; i++) {
if (new String(output[i].Instructor).valueOf().trim()
=== new String(output[k].Instructor).valueOf().trim()) {
output.splice(i, 1);
}
}
}
for (let k = 0; k < output.length; k++) {
console.log(output[k].Instructor);
}
console.log(output.length);
return arr;
}
ngOnInit() {
this.http.get('courses.json').take(1)
.map((res: Response) => res.json())
.subscribe(
data => {
this.list = data;
},
err => console.log(err),
() => this.remove_duplicates(this.list)
);
}
There isn't anything specific to Angular 2 that you're trying to do here. This is just vanilla JS.
Try something like this:
public remove_duplicates(arr) {
let seen = {};
let uniqueInstructorNames = [];
arr.forEach(function(item) {
let instructorNames = item.Instructor.split(',');
Array.prototype.push.apply(uniqueInstructorNames, instructorNames.filter( name => {
return seen.hasOwnProperty(item) ? false : (seen[item] = true);
}));
});
return uniqueInstructorNames;
}

Resources