I'm having trouble converting the follow result from elasticsearch into a different form. Is there a quick way to do this, or would jumping in a for loop be necessary? Thanks in advance:
The format my data is in:
This is how it is in raw format:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
1. 0: Object
1. count: 986
2. term: "virginia"
3. __proto__: Object
2. 1: Object
1. count: 447
2. term: "washington"
3. __proto__: Object
3. 2: Object
1. count: 345
2. term: "newYork"
The Format I need to convert to:
var states= [
{
"key": 'popular',
"values": [
[ 'texas' , 10] ,
[ 'washington' , 5] ,
[ 'new york' , 20] ,
[ 'virginia' , 40]
]
}
];
To help show what the data looks like, this image shows the format from console:
Looking at your sample data, it appears to be an array of objects, each with a term and count property. Array#map would do the trick for converting it into arrays with the term in the first position and the count in the second:
var states= [
{
"key": 'popular',
"values": data.map(function(entry) {
return [entry.term, entry.count];
})
}
];
Live example:
var data = [
{
term: "virginia",
count: 986
},
{
term: "washington",
count: 447
},
{
term: "newYork",
count: 345
}
];
var states= [
{
"key": 'popular',
"values": data.map(function(entry) {
return [entry.term, entry.count];
})
}
];
// Result (I'm only using JSON here as a convenient way to
// display the result; the question doesn't use JSON at all)
var pre = document.createElement('pre');
pre.innerHTML = JSON.stringify(states, null, 2);
document.body.appendChild(pre);
Related
Trying to sort the object with the max date. One id may have multiples dates. Below is the format of the object where id:123 has two dates. So I am trying to take the max date for the user 123. I used the sort method and storing the array[0] but still there is something missing.
var arr = [
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "3212"
},
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
},
{
"score": 20,
"date": "2021-05-05T00:00:00"
}
],
"id": "123"
},
{
"scores": [
{
"score": 5,
"date": "2021-05-05T00:00:00"
}
],
"id": "321"
}
]
What I tried is
_.each(arr, function (users) {
users.scores = users.scores.filter(scores => new Date(Math.max.apply(null, scores.date)));
return users;
});
Expecting the output to look like the following with the max date selected.
[
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "3212"
},
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "123"
},
{
"scores": [
{
"score": 5,
"date": "2021-05-05T00:00:00"
}
],
"id": "321"
}
]
Your filter callback function is not performing a comparison to filter the correct element. Also, although applying the "maximum" algorithm on the dates as string would be fine in your case (because of the date format you have), it would be much safer to transform the date strings into date objects to consistantly get correct results regardless of the format.
In the solution below, you can use a combination of Array.map() and Array.sort() to copy and process your data in the correct result.
const data = [{
'scores': [{
'score': 10,
'date': '2021-06-05T00:00:00'
}],
'id': '3212'
}, {
'scores': [{
'score': 10,
'date': '2021-06-05T00:00:00'
}, {
'score': 20,
'date': '2021-05-05T00:00:00'
}],
'id': '123'
}, {
'scores': [{
'score': 5,
'date': '2021-05-05T00:00:00'
}],
'id': '321'
}];
// map the data and return the updated objects as the result
const result = data.map((user) => {
// copy the scores array to not mutate the original data
const sortedScores = user.scores.slice();
// sort the scores array by date descending
sortedScores.sort((a, b) => (new Date(b.date) - new Date(a.date)));
// return the same user with the first score from the sorted array
return {
...user,
scores: [sortedScores[0]]
};
});
console.log(result);
I want to know how to format my json to have key and value using typescript with Angular framework,
with the current method if I use the keyvalue pipe in my html it will work but I want to format the json.
In my example below I have my Current json and the expected json so that you can see the result I expect and to be as clear as possible being a beginner in the business I wanted to be clear
Current.json
{
"url": "url test"
"flight": [
[
"1",
"apollo",
"ariane"
],
[
"2",
"Space X",
"Boca chica"
]
]
}
expected.json // this json is what I would like to have
{
"url": "url test"
"flight": [
[
id: "1",
name: "apollo",
rocket:"ariane"
],
[
id: "2",
name: "Space X",
rocket: "falcon 9"
]
]
}
ts.file
get() {
this.service.get().subscribe((data: Interface[])=> {
this.array = data
});
Your expected Json isn’t valid, if you want property names for those array values you need to make them an object.
{
"url": "url test"
"flight": [
{
id: "1",
name: "apollo",
rocket:"ariane"
},
{
id: "2",
name: "Space X",
rocket: "falcon 9"
}
]
}
To get this format from the example you gave you can do this:
get() {
this.service.get().subscribe((data: Interface[])=> {
data.flight = data.flight.map(f => ({id: f[0], name: f[1], rocket: f[2]}))
this.array = data
});
Please try this code snippet
get() {
this.service.get().subscribe((data: any)=> {
data.flight = data.flight.map(f => {
return {id: f[0], name: f[1], rocket: f[2]}
})
this.array = data
});
I had this JSON:
"event": [
{
"timestamp": "2016-10-02T11:37:31.2300892-03:00",
"revenue": 120.0,
"transaction_id": "3409340",
"store_name": "BH Shopping",
"products": []
}
And this Object Array:
[ { name: 'Blue Shirt', price: 100 },
{ name: 'Nike Shoes', price: 150 } ]
How can I add the Object Array into the products Array inside the JSON using Javascript?
Please check this solution of adding objects to object property:
var jsonStr = '{"event": {"timestamp": "2016-10-02T11:37:31.2300892-03:00", "revenue": "120.0", "transaction_id": "3409340", "store_name": "BH Shopping", "products": []}}';
var obj = JSON.parse(jsonStr);
obj['event']['products'].push({"name":"Blue Shirt","price":"100"});
obj['event']['products'].push({"name":"Nike Shoes","price":"150"});
jsonStr = JSON.stringify(obj);
console.log(jsonStr);
From the look of it, event is a JSON Array on its own so to target the first one you will have to pict JSON Object at index 0.
var eventObject = event[0];
Now the products is an array and you can push staff into it by iterating over your Object Array
objectArray.forEach(function(object){
//the object is each array item
eventObject.products.push(object);
});
I have an array of objects. if i do a console.log, i can see these array of objects.
[Object, Object, Object, Object,Object]
[0-4]
0:Object
Name: Nikhil
User_ID:123
admin:true
read:false
write:false
1:Object
Name:andy
User_ID:124
admin:false
read:true
write:false
2:Object
Name:Nik
User_ID:125
admin:false
read:false
write:true
3:Object
Name:ranea
User_ID:126
admin:false
read:false
write:true
4:Object
Name:isha
User_ID:127
admin:false
read:true
write:false
Now, if i do JSON.stringify, i get this output.
[{"Name":"Nikhil","User_ID":"123","admin":true,"read":false,"write":false},
{"Name":"andy","User_ID":"124","admin":false,"read":true,"write":false},
{"Name":"Nik","User_ID":"125","admin":false,"read":false,"write":true},
{"Name":"ranea","User_ID":"126","admin":false,"read":false,"write":true},
{"Name":"isha","User_ID":"127","admin":false,"read":true,"write":false}]
Instead of doing stringify to all the parameters, I want to only do it to few. For e.g. I don't want to pass Name. I only want to pass User_ID since it is unique, and admin,read,write properties.
How can i create a new array of objects using loadash and then stringify the result. My final output after JSON.stringify should be like this
[{"User_ID":"123","admin":true,"read":false,"write":false},
{"User_ID":"124","admin":false,"read":true,"write":false},
{"User_ID":"125","admin":false,"read":false,"write":true},
{"User_ID":"126","admin":false,"read":false,"write":true},
{"User_ID":"127","admin":false,"read":true,"write":false}]
Using _.pick it should be:
var newArr = _.map(oldArray,
function(item) {
return _.pick(item, ['User_ID', 'admin', 'read', 'write']);
});
You could make use of the Array.map() function.
var obj = [ { "Name": "Christophe", "Age": 42, "foo": "bar" }, { "Name": "Blah", "Age": 42, "foo": "foo2" }]
var filtered = obj.map(function (element) {
return {
"Name": element.Name
}
});
After that, filtered contains your objects with only the keys you want to keep, and you can JSON.stringify it.
console.log(JSON.stringify(filtered));
// [ {"Name": "Christophe"}, {"Name": "Blah"} ]
You can use this little function to return
the new Array.
var arr = [{
Name: "Nikhil",
User_ID: "123",
admin: "true",
read: "false",
write: "false"
}, {
Name: "andy",
User_ID: "124",
admin: "false",
read: "true",
write: "false"
}];
function returnArr(array) {
var arrNew = arr;
for (let in arrNew) {
delete arrNew[let].Name;
}
return JSON.stringify(arrNew);
}
document.write(returnArr(arr)); // or console.log(returnArr(arr))
Im new to JSON and I have to deal with a complex one.
Please see image below:
It has an error:
I don't know how to properly separate the 2 json arrays. I even tried to use : instead of , on line 18 but I still get errors. BTW, I use http://jsonlint.com/ to validate.
On line 2 you gave a key, but failed to do so on line 19. You have to keep the structure.
Remove the key on line 2, they shouldn't be used for arrays in that way.
Edit: In addition, you are trying to put arrays right in objects, switch the opening and ending object marks ({}) with ([]) for arrays on your first and last line.
[
[
{...},
{...},
...
{...}
],
[
{...},
{...},
...
{...}
],
...
[
{...},
{...},
...
{...}
]
]
I believe the correct way to build this JSON should be:
{
"glEntries": [
{
"generalLedgerId":1,
"accountId": 34,
"amount" : 32334.23,
"descripction": "desc1",
"debit" : "Yes"
},
{
"generalLedgerId":2,
"accountId": 35,
"amount" : 323.23,
"descripction": "desc",
"debit" : "Yes"
},
...
]
}
There are many ways to construct JSON data, but it depends on your data and the way you want to present it. Here are a couple examples - hope it helps:
{
"glEntries": [
{
"object1-prop1": "one"
},
{
"object2-prop1": 1,
"object2-prop2": "two"
},
{
"object3-prop1": [
"a",
"r",
"r",
"a",
"y"
],
"object3-prop1.1": "string"
}
],
"otherEntries": [
{
"objectx": "x"
},
{
"objecty": "y"
},
{
"objectz": [
1,
2,
3,
4
]
}
],
"oneEntry": "json"
}
Other Example:
[
{
"obj1-prop": 222
},
{
"obj2-prop": "object2"
},
{
"obj3-prop": "Object3"
},
[
"a",
"r",
"r",
"a",
"y",
777,
888
],
"string",
178,
{
"objectProp": "testing123"
}
]
You have more {} than needed and will make parsing your JSON more difficult:
Structure will work a lot better like this:
{"glentries":[
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"},
{ "property1":"value", "property2" : "value",..... "lastProperty": "value"}
]
}
Now glentries is an array of objects that have multiple properties to them.
alert( glentries[0].property2 )
The parent structure is an Object, so it is expecting a string Key for the second array. It it's supposed to be an array of arrays, you should be using an array and not an Object.