How to have a result array when using autocomplete in Angular 6 - arrays

I want to create a array with id of products.
I have this form:
this.myform= new FormGroup({
'products_id': this.fb.array([], Validators.required),
'unit_price': new FormControl('', [Validators.required)
});
My function submit is:
onAddProducts() {
this.areWeWaiting = true;
let newp = this.myform.value
let newprod= new Products(
newp
);
this.ws.createP(newprod).subscribe(
result => {
if (result === true) {
} else {
this.areWeWaiting = false;
}
},
error => {
this.areWeWaiting = false;
}
);
}
Result from this code is this array: ["Y4FQS", "qOKTN", "sRm54"]
I want to have a result like this: ["1", "2", "3"] I want to submit Id of product, not name of product.
For this I try to change my code like this:
I declare a property prodId: Array<string>[]; and in function submit:
onAddProducts() {
this.areWeWaiting = true;
let newp = this.myform.value
newp.products_id= this.prodId;
let newprod= new Products(
newp
); ........}
This prodId I take form this function:
updateForm(ev: any, idd: any, componentid: any) {
if (ev.isUserInput) {
if (componentid === 'products_id') {
this.prodId = idd;
this.myForm['controls']['products_id'].setValue(ev.source.value);
} else {
console.log('ooops');
}
}
}
This is a function that get all product from API:
this.ws.getAllproducts().subscribe(
products=> {
this.products= products.map((prod) => {
this.filteredProducts = this.myForm.controls['products_id'].valueChanges
.pipe(
startWith(''),
map(value => this._filters(value))
);
return new Products(prod);
});
}
);
this function return:
{
"StatusCode": 0,
"StatusMessage": "OK",
"StatusDescription": [
{
"products_id": "1",
"products_name": "PkMGo",
"unit_price": 100,
},
{
"products_id": "2",
"products_name": "Y4FQS",
"unit_price": 100,
},
{
"products_id": "3",
"products_name": "Mlld0",
"unit_price": 100,
},
{
"products_id": "4",
"products_name": "q0KTN",
"unit_price": 100,
},...
]
}
This code show me only id of the latest product like "3"
Can you ask me any idea please, how to post an array like ["1", "2", "3"]
Thank you!

Related

How to fetch two or more json file data in one page

for example, in my project, I have 4 steps, in 2 steps already pass (class id and subject id)the JSON, now I want to know how to add two JSON on a one-page example topic list
[
{
"_IdTopicMaster": "1",
"TopicName": "demo1",
"IdSubjectMaster": "1"
},
]
Contentlist JSON here
{
"IdContentMaster": "11",
"IdTopicMaster": "1",
"IdContentTypes": "2",
"DisplayName": "contentdemoname",
"ContentPath": "demo/Kannada/G1/Maths/VML",
"ContentName": "KG1MVML1.1 ",
"thumbnail": "assets/application/icons/Englishmedium/Class 1/Maths/dummy.png",
"format": ".mp4"
},
here is my JSON function code
Future<void> getListOfMonths() async {
final String fileText = await
rootBundle.loadString('assets/database_json/contentlist.json');
Map<String, dynamic> user = jsonDecode(fileText);
List<dynamic> list = user['data'];
for (int i = 0; i < list.length; i++) {
if (selectedtl == int.parse(list[i]['Class_id'])) {
if (selectedsubtopic == int.parse(list[i]['IdSubjectMaster'])) {
if (selectedModules == int.parse(list[i]['_IdTopicMaster'])) {
listOfWeekWidgets.add(GestureDetector(
onTap: () {
filePath = list[i]['ContentPath'];
fileName = list[i]['ContentName'];
cpformat = list[i]['format'];
subTopName = list[i]['SubjectName'];
checkIfPathIsPicked(int.parse(list[i]["_IdTopicMaster"]));
},
child: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) {
return Container();
}),
));
setState(() {
listOfWeekWidgets;
});
}
}
}
}
}

Replace a string in array of objects in typescript

I have got a list of array objects as shown below
[
{
"subjectID": 1
"Chosen" : "{subjectsChosen:Python,java,Angular}"
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}"
"password": "{studentpw:987654zyxwv}"
}
]
Here I would like to remove the special characters and its notations and expected to populate array as shown below using typescript
[
{
"subjectID": 1
"Chosen" : "Python,java,Angular"
"password": "23456abcd"
},
{
"subjectID": 2
"Chosen" : "SQL,Rprogram,React"
"password": "987654zyxwv"
}
]
Thank you in advance
try this
for (let i = 0; i < subs.length; i++) {
subs[i].Chosen = removeSymbols(subs[i].Chosen);
subs[i].password = removeSymbols(subs[i].password);
}
function removeSymbols(s: string) {
return s.replace(/[\{\}]/g, "").split(":")[1];
}
result
[
{
"subjectID": 1,
"Chosen": "Python,java,Angular",
"password": "123456abcd"
},
{
"subjectID": 2,
"Chosen": "SQL,Rprogram,React",
"password": "987654zyxwv"
}
]
Welcome, is your object properties special characters limited to '{', ':', '}', if so, I propose to you the bellow solution, that I have tried and give a result as the one you have expected:
let objs = [
{
subjectID: 1,
Chosen: "{subjectsChosen:Python,java,Angular}",
password: "{studentpw:123456abcd}"
},
{
subjectID: 2,
Chosen: "{subjectsChosen:SQL,Rprogram,React}",
password: "{studentpw:987654zyxwv}",
}
];
objs.forEach((cur) => {
Object.keys(cur).forEach(key => {
if (typeof cur[key] === 'string') {
cur[key]=cur[key].replace(/[\{\}]/g, '').split(':')[1];
}
})
});
console.log(objs);
You could use any array operator function other than forEach.
We could use map operator of Array here to transform each item. To transform Chosen and password fields, we could use Regex and replace method of string.
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const myText = "{subjectsChosen:Python,java,Angular}";
myText.replace(re, '$1'); // Python,java,Angular
Below is the full implementation that transform each item.
const items = [
{
"subjectID": 1,
"Chosen" : "{subjectsChosen:Python,java,Angular}",
"password": "{studentpw:123456abcd}"
},
{
"subjectID": 2,
"Chosen" : "{subjectsChosen:SQL,Rprogram,React}",
"password": "{studentpw:987654zyxwv}"
}
];
const chosenRegex = new RegExp(/\{subjectsChosen:(.+)\}/, 'i')
const passwordRegex = new RegExp(/\{studentpw:(.+)\}/, 'i')
const transformedItems = items.map(item => {
return {
...item,
"Chosen": item.Chosen.replace(chosenRegex, '$1'),
"password": item.password.replace(passwordRegex, '$1')
}
});
console.log(transformedItems);
We could also literally use a single regex if we don't want to differentiate them.
const transformRegex = new RegExp(/\{(.+):(.+)\}/, 'i');
....
return {
...item,
"Chosen": item.Chosen.replace(transformRegex, '$2'), // Since there are two regex groups now, use $2
"password": item.password.replace(transformRegex, '$2')
}

ES6 : Create objects in a given format from array of key values

var result = {445: "L005.0", 455: "L006.0", 456: "L007.0", 457: "L008.0", 458: "L009.0", 459: "L027.0", 467: "L005.7", 580: "L001.0", 581: "L002.0", 587: "L003.0"};
From this "result", I want to output an object like this
{
"445": {
name: result[445],
icon: "fa-search"
},
"455": {
name: result[455],
icon: "fa-search"
},
"456": { ... },
"457": { ... },
...
...
}
So you need to iterate over keys to construct new object o;
let res={}; //initializing
for(let i of Object.keys(result))
{
res[i]={
"name": result[i],
"icon":"fa-seach"
}
}
console.log(res) //to test

How to Filter Object Fields by a String Array

How can I filter an Object's field by an string array?
eg.
catValues:{
"1":{
value:10,
code:5
},
"3":{
value:10,
code:5
},
"5":{
value:10,
code:5
}
}
var chosenCats = ["1","5"]
result: {"1":{value:10, code:5}, "5":{value:10, code:5}}
You create a new object and insert just the chosen cat values.
var chosenCatValues = {};
for (var cat of chosenCats) {
chosenCatValues[cat] = catValues[cat];
}
Or you can use filter() and reduce():
var chosenCatValues = Object.keys(catValues)
.filter(key => chosenCats.includes(key))
.reduce((obj, key) => {
obj[key] = catValues[key];
return obj;
}, {});
Demo:
var catValues = {
"1": {
value: 10,
code: 5
},
"3": {
value: 10,
code: 5
},
"5": {
value: 10,
code: 5
}
};
var chosenCats = ["1", "5"];
var chosenCatValues = Object.keys(catValues)
.filter(key => chosenCats.includes(key))
.reduce((obj, key) => {
obj[key] = catValues[key];
return obj;
}, {});
console.log(chosenCatValues);
Try this:
Note: This will work with array of strings as well considering they are numbers.
var catValues = {
"1":{
value:10,
code:5
},
"3":{
value:10,
code:5
},
"5":{
value:10,
code:5
}
}
var chosen = ['1','5'];
const func = (chosen, catValues) => {
var ch = {};
chosen.map(chose => {
if(chose in catValues) {
ch[chose] = catValues[chose]
}
})
return ch
}
console.log(func(chosen, catValues))

How best to Compare JSON object values to a fixed array in JScript

I would like to compare JSON values to an array of values but I d'ont know what's the best scenario to go with.
I got a JSON object with expected values (could have 1 value , 2 or more)
I have a DB function that returns a fix number of values, say 10 values all the time and I would like to know if my JSON values matches the right one coming from DB.
Ex:
My JSON var is :
var expValues = {
"id": "123",
"age": 23
};
My DB will push some values to an Array of objects.
Ex:
if ((rs.BOF) && (rs.EOF))
{
//nothing found;
}
else
{
while (!rs.EOF)
{
aDetails.push(
{
"id": rs.fields("id").Value,
"name": rs.fields("name").Value,
"age": rs.fields("age").Value,
"sex": rs.fields("sex").Value,
"hobby": rs.fields("hobby").Value
});
rs.MoveNext();
}
}
rs.close;
//Close connection then return
return aDetails;
basically I want to make sure values coming from JSON match the right ones coming from DB. (id for example).
I have assumed aDetails to have something like below data.
let aDetails = [{
"id": "123",
"name": "as",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "1234",
"name": "as1",
"age": 23,
"sex": "m",
"hobby": "abc"
}, {
"id": "12",
"name": "as2",
"age": 23,
"sex": "m",
"hobby": "abc"
}]
var expValues = {
"id": "123",
"age": 23
};
function isObjectMatched(obj) {
return aDetails.some(d => Object.entries(obj).every(([k, v]) => d[k] == v))
}
console.log(isObjectMatched(expValues))
This is a general purpose way of indexing list of objects for fast retrieval with any configuration of properties.
// javascript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
listOfPropertyToIndex.forEach((p) => {
key.push(""+o[p]);
});
return key.join("_");
};
arrayOfObject.forEach((o) => {
index[objToKey(o)] = o;
});
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
// jscript version
function makeIndex (arrayOfObject, listOfPropertyToIndex) {
var index = {};
index.objToKey = function (o) {
var key = [];
for (var p in o) {
if (o.hasOwnProperty(p)) {
key.push(""+o[p]);
}
}
return key.join("_");
};
for (var i = 0; i < arrayOfObject.length; ++i) {
index[objToKey(arrayOfObject[i])] = o;
}
index.match = function (object) {
var key = index.objToKey(object);
if (index.hasOwnProperty(key)) {
return index[key];
};
return null;
});
return index;
}
Here is how to use it
var expValues = {
"id": "123",
"age": 23
};
var index = makeIndex(aDetails, ["id","age"]);
var obj = index.match(expValues);
if (obj) {
... obj ...
}
var index_name = makeIndex(aDetails, ["name"]);
var person = {"name":"as2"};
var obj2 = index_name.match(person);
if (obj2) {
... obj2 ...
}

Resources