How to update old value with new value in array [React native] - arrays

I have array
[{
"studentname": "abc",
"marks": "20"
},
{
"studentname": "abc2",
"marks": "20"
}
]
I have want add 10 more marks where studentname=abc into marks so how do this
eg.10+20=30
so the output will be
[{
"studentname": "abc",
"marks": "30"
},
{
"studentname": "abc2",
"marks": "20"
}
]

const updatedArray = array.map(item => {
if (item.studentname === "abc") {
return {
studentname: "abc",
marks: parseInt(item.marks, 10) + 10
};
} else {
return item;
}
});

This is one clean way to do it.
const x= [{
"studentname": "abc",
"marks": "20"
},
{
"studentname": "abc2",
"marks": "20"
}
]
x.forEach(function(obj) {
if (obj.studentname === 'abc') {
obj.marks = Number(obj.marks) + 10
}
});
console.log(x)

const array= [{
"studentname": "abc",
"marks": "20"
},
{
"studentname": "abc2",
"marks": "20"
}
]
array.map((item,index)=> {
if (item.studentname == 'abc') {
item.marks = Number(item.marks) + 10
}
});
console.log("Your Updated Array Here:->",array)

Loop through the array of objects
Check if the studentname property of the current object is equal to abc
If it is, add 10 to the marks property of the current object
After the loop, the array will be updated with the modified object
const arr = [{"studentname": "abc", "marks": "20"},
{"studentname": "abc2","marks": "20" }];
for (let i = 0; i < arr.length; i++) {
if (arr[i].studentname === "abc") {
arr[i].marks = parseInt(arr[i].marks) + 10;
}
}
console.log(arr);

Related

How to filter a nested array of dictionaries with multiple conditions from another array in Swift

sample json data is this:
{
"variations": [
{
"variation_id": 391,
"name": "Fruit Shake - Chocolate, S",
"price": 10,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Chocolate"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "S"
}
]
},
{
"variation_id": 385,
"name": "Fruit Shake - Banana, L",
"price": 18,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "L"
}
]
},
{
"variation_id": 386,
"name": "Fruit Shake - Banana, M",
"price": 15,
"attribute": [
{
"attribute_key": "pa_flavor",
"name": "Flavor",
"option": "Banana"
},
{
"attribute_key": "pa_size",
"name": "Size",
"option": "M"
}
]
}
]
}
my problem is, getting the variation_id where 2 or more attributes matches the array of string.
for example, chosenProduct = ["Banana", "L"]
I tried filter and contains but theres no way to match the other item from chosenProduct.
If I added the next condition, it returns nil
You can try this:
let varID = product.variations?.filter { att in
var matchedAttributes = 0
for thisAttribute in att.attribute {
if chosenProduct.contains(where: {$0 == thisAttribute.option}) {
matchedAttributes += 1
}
}
if matchedAttributes >= 2 {
return true
}
return false
}
Let me know if there's any doubt.
You can try this :
var chosenProduct = ["Banana","L"]
var expectedIds : [Int] = [Int]()
datas.variations?.map{ val in
val.attribute.map({ val2 in
let filtered = val2.enumerated().filter({chosenProduct.contains($0.element.option!)})
if filtered.count == chosenProduct.count{
expectedIds.append(val.variation_id!)
}
})
}
print(expectedIds) // [385]
I put the id's in array because of if you want to change your chosenProcudt example "Banana" (count 1 ). This mapping must be return variation_id like [385,386]
You can a method to Variation to make things easier:
extension Variation {
func attributesMatching(options: [String]) -> [Attribute] {
attribute.filter { options.contains($0.option) }
}
}
Then, you can just write:
let filtered = product.variations.filter { $0.attributesMatching(options: chosenProductOptions).count >= 2 }
print(filtered.map { $0.variationID })

I can't use filter when I have objects inside an array and find last id, angular

I need your opinion in this situation:
I get from API with this function:
getRS(
idProject: string
): Observable<ResponseModel<RSModel>> {
return this.http.get<ResponseModel<RSModel>>(
ApiUrlsConfig.getRS(
idProject
)
);
}
this response:
{
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3",
}
],
"result": null
}
I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
#Input() set jobId(jobId: string) {
this.optionsService
.getRS(
this.idProject
)
.pipe()
.subscribe((res) => {
let resId = res.filter((aaa)=>{
if(aaa.id === jobId){
res.slice(-1)[0].id
}
}
)
});
}
Not function.
Please can you share with me any idea?
Thank you
Try this logic:
Loop backwards throw it.
Loop backwards over index to the start.
Splice duplicates.
let response = {
"data": [
{
"id": "id1",
"state": 1,
"note": null
},
{
"id": "id1",
"state": 2,
"note": "Reason 1"
},
{
"id": "id2",
"state": 2,
"note": "Reason updated3"
}
],
"result": null
}
let data = response.data;
for (let i = data.length - 1; i >= 0; i--) {
for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
data.splice(j, 1);
j++;
}
}
};
console.log(data);
try this:
if(aaa.id == jobId){
return res.slice(-1)[0].id
}

Sort and group objects alphabetically by the first letter from an array in Angular?

How can I sort and group objects alphabetically by the first letter from an array in angular? I have seen the example to do this Sort and group objects alphabetically in Javascript and the exact answer and output json i am looking in Angular.
As of now My api json is like this stackblitz
Expexted api json would like this stackblitz
I have tried this but i am unable to found the solution in angular.
real Json:
employees = [
{ name: "Abigail", age: "25" },
{ name: "Axle", age: "29" },
{ name: "Brianna", age: "25" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Charlotte", age: "28" },
{ name: "David", age: "22" }
];
expecting json after sort and group objects alphabetically by the first letter from an array would like:
[
{
"alphabet": "A",
"record": [
{ "name": "Abigail", "age": "25" },
{ "name": "Axle", "age": "29" }
]
},
{
"alphabet": "B",
"record": [
{ "name": "Brianna", "age": "25" },
{ "name": "Brooklyn", "age": "23" }
]
},
{
"alphabet": "C",
"record": [
{ "name": "Camila", "age": "24" },
{ "name": "Charlotte", "age": "28" }
]
},
{
"alphabet": "D", "record": [
{ "name": "David", "age": "22" }
]
}
]
expected output like:
A
Abigail
Axle
B
Brianna
Brooklyn
C
Camila
Charlotte
D
David
As mentioned in the comment, there is no Typescript specific way to sort and group the data. You could the JS Array#reduce to group the objects to your requirement.
Try the following
const employees = [ { name: "Abigail", age: "25" }, { name: "Axle", age: "29" }, { name: "Brianna", age: "25" }, { name: "Brooklyn", age: "23" }, { name: "Camila", age: "24" }, { name: "Charlotte", age: "28" }, { name: "David", age: "22" } ];
const output = employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
}
else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => r1.name > r2.name ? 1 : -1);
}
return acc;
}, [])
.sort((e1, e2) => e1.alphabet > e2.alphabet ? 1 : -1);
console.log(output);
It would look like following in the Stackblitz.
export class ExpansionOverviewExample {
#ViewChild(MatAccordion, { static: false }) accordion: MatAccordion;
employees = [
{ name: "Brianna", age: "25" },
{ name: "Axle", age: "29" },
{ name: "David", age: "22" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Abigail", age: "25" },
{ name: "Charlotte", age: "28" }
];
constructor() {
this.employees = this.employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
} else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => (r1.name > r2.name ? 1 : -1));
}
return acc;
}, [])
.sort((e1, e2) => (e1.alphabet > e2.alphabet ? 1 : -1));
}
}
You could also use safe navigation operator ?. in the template so you don't get any undefined errors before the reduce is complete.
<div *ngFor="let mani of employees">
<div>
<p>{{mani?.alphabet}}</p>
<p *ngFor="let group of mani?.record"> {{ group?.name }}</p>
<hr>
</div>
</div>
I've updated your Stackblitz

Conversion of list of JSON array to a single object in Angular

I have an array list which needs to be converted to a single object with few of the values from array list using TypeScript in Angular 8. Below is the array:
"arrayList": [{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
]
This needs to be converted to the below format,
data: {
"Testname1": "abc",
"Testname2": "xyz",
}
No matter how much i try, i end up creating a list instead of a single object. Can you please help on the same?
You can use as follows,
var arr = [
{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
];
var result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].name] = arr[i].value;
}
console.log(result);
Try with using .reduce() as the following:
const arrayList = [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" }];
const data = arrayList.reduce((a, {name, value}) => {
a[name] = value;
return a;
}, {});
const result = { data };
console.log(result);
Use Array.map() to get a list of [name, value] entries, then use Object.fromEntries() to convert to an object:
const arrayList = [{ "name": "Testname1", "value": "abc" }, { "name": "Testname2", "value": "xyz" }];
const result = Object.fromEntries(arrayList.map(({ name, value }) => [name, value]));
console.log(result);
Please use the below code
const rawData = {
"arrayList": [{
"name": "Testname1",
"value": "abc"
},
{
"name": "Testname2",
"value": "xyz"
}
]
};
const updatedData = {
data: {}
};
for (const item of rawData["arrayList"]) {
updatedData.data[item.name] = item.value;
}
console.log(updatedData);

how to add 2 element in nested array from one root element using JOLT specification?

Input:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Expected output:
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY",
"arr": [
{
"k1": "v1",
"key": "first"
},
{
"k2": "v2",
"key": "second"
},
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary1": "s2",
"key": "SUMMARY"
}
]
}
For each 'k1' and 'k2', respective array element should be added as
{
"k2": "v2",
"key": "second"
}
For when event = "SUMMARY", respective 2 elements should be added as
{
"summary1": "s1",
"key": "SUMMARY"
},
{
"summary2": "s2",
"key": "SUMMARY"
}
Please help with JOLT specification
Since you gave input and output based on that i written
one function in javascript.
{
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
Well that function will work only for above input
and also you have to mention that whether u want output in which language...
//Input
var obj = {
"k1": "v1",
"k2": "v2",
"event": "SUMMARY"
}
//funciton calling
obj["arr"] = checkThis(obj);
//output
console.log(obj)
function checkThis(obj) {
var arr = [];
Object.keys(obj)
.forEach(function eachKey(key) {
if (key == "k1") {
var tempObj = {}
tempObj["k1"] = obj[key];
tempObj["key"] = "first";
arr.push(tempObj)
} else if (key == "k2") {
var tempObj = {}
tempObj["k2"] = obj[key];
tempObj["key"] = "second";
arr.push(tempObj)
} else if (key == "event") {
var tempObj1 = {}
var tempObj2 = {}
tempObj1["summary1"] = "s1";
tempObj1["key"] = obj[key];
tempObj2["summary1"] = "s2";
tempObj2["key"] = obj[key];
arr.push(tempObj1)
arr.push(tempObj2)
}
});
return arr;
}

Resources