Create a new JSON after manipulating json values in angular6 - json

Below is my JSON
[
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
}
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
}
]
First i want to split key value by backslash and after that will split the [2] json value by hyphen and then will check in string that if there is SUCCESS/PENDING/ERROR word found in the newly spitted JSON. If any word is present would like to add new status field and add Done/Processing/Failure respective values in newly created JSON. this is a dynamic json so without manipulating it i can't get status value
This is what i would like to achive in my new JSON
[
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx",
"status":"Failure"
}
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx",
"Status":"Done"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx",
"Status":"Processing"
}
]
As i'm new to this kindly let me know how to achieve this

You can use includes function and if true then add string.
Try my code:
let myJson = [
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/WRONG-doc-20200103.xlsx"
}
];
myJson = myJson.map(obj => ({
...obj,
"Status": obj.Key.includes("ERROR") ? 'Failure' : obj.Key.includes('SUCCESS') ? 'Done' : obj.Key.includes('PENDING') ? 'Processing' : false
}))
console.log(myJson)

for(let object of objectArra) {
if(object.key === 'doc....')
object['status']="Failure";
else if (object.key === 'doc..')
object['status'] = "Done";
else if....
}
Iterate on object array if the key is equal to that you want status is "failure", you insert a status property in the object with "Failure" as value ...

This can be achieved in the following way
yourArrayName.forEach((val)=>{
if(val.Key.includes('ERROR')){
val['Status']="Failure"
}
else if(val.Key.includes('SUCCESS')){
val['Status']="Done"
}
else if(val.Key.includes('PENDING')){
val['Status']="Processing"
}
})
Hope it helps!

How to do it in ES 6
The key advantage is the use of Regex which makes it more flexible to other requirements than includes.
const data = [
{
"Key": "doc/1996-78/ERROR-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx"
},
{
"Key": "doc/1996-78/PENDING-doc-20200103.xlsx"
}
];
data.map((entry) => {
let status;
if (/^.*ERROR.*$/.test(entry.Key)) {
status = 'Failure';
} else if (/^.*SUCCESS.*$/.test(entry.Key)) {
status = 'Done'
} else if (/^.*PENDING.*$/.test(entry.Key)) {
status = 'Processing'
}
return {...entry, status};
});

Related

update value of a map of objects

With jq, how can I transform the following:
{
"root": {
"branch1": {
"leaf": 1
},
"branch2": {
"leaf": 2
},
"branch3": {
"leaf": 3
}
},
"another-root": {
"branch": 123
},
"foo": "bar"
}
to this:
{
"root": {
"branch1": {
"leaf": "updated"
},
"branch2": {
"leaf": "updated"
},
"branch3": {
"leaf": "updated"
}
},
"another-root": {
"branch": 123
},
"foo": "bar"
}
🤦 Apparently [] can be used on object too. I had though it was only for lists.
The following was all I needed.
.root[].leaf="updated"
First you need to parse the json and then modify the resulting object as required using for ... in statement (example below)
const flatJSON = '{"root":{"branch1":{"leaf":1},"branch2":{"leaf":2},"branch3":{"leaf":3}},"another-root":{"branch":123},"foo":"bar"}';
const parsedJSON = JSON.parse(flatJSON);
const root = parsedJSON.root;
for (let property in root) {
root[property].leaf = "updated"; (or root[property]["leaf"] = "updated";)
}
If you want to use jquery you have to replace for ... in statement with jQuery.each() method that iterates over both objects and arrays.
Don't forget to convert it back to json with JSON.stringify() method (if required).
Hope that this helps.
All the best.

check for duplicate date from data and assign to new one json

i have a json which contain duplicate date , i want to merge duplicate date into single json object.
Data:
[
{"date":"2017-06-26","mac":"66"},
{"date":"2017-06-26","window":"400"},
{"date":"2017-07-03","mac":"19"},
{"date":"2017-07-03","window":"12"}
]
output should be:
[
{"date":"2017-06-26","mac":"66","window":"400"},
{"date":"2017-07-03","mac":"19","window":"12"}
]
Here a javascript function that does that, you can apply JSON.stringify(...) to the output after passing your array and obtain the new json.
(( a ) => {
// used to check for already inserted dates
let withoutDupes = { };
if(Array.isArray(a)) {
a.forEach( (item) => {
// assuming item has a "date" property inside
if(withoutDupes[item.date]) {
withoutDupes[item.date] = Object.assign( item, withoutDupes[item.date] );
} else {
withoutDupes[item.date] = item;
}
} );
}
return Object.values( withoutDupes );
})( a )
You can try using jq command line parser and its group_by function:
jq '[group_by(.date)|.[]|add]' file
[
{
"date": "2017-06-26",
"mac": "66",
"window": "400"
},
{
"date": "2017-07-03",
"mac": "19",
"window": "12"
}
]

How to remove objoct from object by finding in type script

This is my object
"filterValue":[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}},
]
from this i want to search where value.Id = 2 and i want to remove that obeject line.
how can i do that..?
note:first value will be empty there is no data in value.
i have tried something like this:
filterValue.splice( filterValue.indexOf(2), 1 );
You can't use indexOf in this case because you are checking a complex object but you can use findIndex like this:
filterValue.splice( filterValue.findIndex(a => a.Id == 2), 1 );
You might want to change the code the check if findIndex actually found something by checking if it returns something larger than (or equal to) 0.
You can use filter to get a new filtered array (filteredArr):
var arr = [
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1",}},
{"label":"abc.def","value":{"Id":"2",}},
{"label":"asd.vdf","value":{"Id":"3",}}
];
var filteredArr = arr.filter((x) => JSON.stringify(x.value) !== JSON.stringify({"Id":"2"}));
console.log(filteredArr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You have a couple of subtly traps to avoid with your specific example.
The structure of items differs, so you need to be careful that you don't have a problem with the "--Select a Member--" item, which doesn't have a value.Id.
The example below cheaply solves the type issue (the best common type between the array members doesn't contain the property you are interested in).
const items = [
{ "label": "--Select a Member--", "value": "" },
{ "label": "ghi.jkl", "value": { "Id": "1", } },
{ "label": "abc.def", "value": { "Id": "2", } },
{ "label": "asd.vdf", "value": { "Id": "3", } },
];
const filtered = items.filter((i: any) => !i.value || !i.value.Id || i.value.Id !== '2');
console.log(filtered);
Output:
[
{"label":"--Select a Member--","value":""},
{"label":"ghi.jkl","value":{"Id":"1"}},
{"label":"asd.vdf","value":{"Id":"3"}}
]
const obj = {
filterValue: [
{ label: "--Select a Member--", value: "" },
{ label: "ghi.jkl", value: { Id: "1" } },
{ label: "abc.def", value: { Id: "2" } },
{ label: "asd.vdf", value: { Id: "3" } }
]
};
var changedObj = obj.filterValue.filter((data, index) => {
return data.value.Id != "1";
});
console.log(changedObj);

How to update a key value in JSON dynamically?

I have a JSON like below
{
"context":{
"parameters":[
{
"name":"stub",``
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
I am supplied with a two strings dynamically like "cars" and "accord". I need to search for "cars" and then replace the "item value" under it to "accord". I have tried to convert it to map but have no success.
Any suggestions about how I can achieve this?
Here's one way to do it in Groovy.
Assuming that the JSON is like so (I have corrected it; there are illegal chars in the original question):
def s = '''
{
"context":{
"parameters":[
{
"name":"stub",
"value": {"item value":"abcdefg"}
},
{
"name":"category",
"value":{"item value":"cars"}
},
{
"name":"year",
"value":{"item value":"2012"}
},
{
"name":"make",
"value":{"item value":"toyota"}
},
{
"name":"cars",
"value":{"item value":"corolla"}
}
]
}
}
'''
then consider:
import groovy.json.*
def jsonSlurper = new JsonSlurper().parseText(s)
def category = jsonSlurper.context.parameters.find { it.name == "cars" }
category.value."item value" = "accord"
println new JsonBuilder(jsonSlurper).toPrettyString()
you can do that with javascript. If you are working with JSON format you can parse that data to an object.
const data = JSON.parse("your json data")
data.context.parameters.map(param => {
if ( param.name !== "cars") {
return param
}
return {
"name": "cars",
value: {"accord": "corolla"}
}
})

How to get total no of count of a field in a Json Array using TypeScript

I have a Json array.
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
Here I want to get the count of total number of customer. I am getting it like this:
json.user.value.length;
And the output is 3. But the thing is I have to avoid duplicate customer number.
As here "1234" is there 2 times. So my output should be 2
How to do this using Typescript.
Use lodash:
var uniqueCustomer = _.uniqBy(json.user.value, 'customerNo');
var length = uniqueCustomer.length
Here is link which shows How to use lodash in your app.
You can use Array.reduce to count the unique customers.
const data = {
"user": {
"value": [
{
"customerNo": "1234"
},
{
"customerNo": "abcd"
},
{
"customerNo": "1234"
}
]
}
};
function getCustomerCount(arr) {
let tmp = [];
return arr.reduce((acc, curr) => {
if(!tmp.includes(curr.customerNo)) {
return tmp.push(curr.customerNo);
}
return acc;
}, 0);
}
let customers = data.user.value;
let customerCount = getCustomerCount(customers);
console.log(customerCount);