Create new Single Object from an ArrayObject - angularjs

I want an Object which I can simply change to JSON format for Exporting later on.
For this I have an array of objects like this:
[
{
"name": "Test",
"value": "EN Test"
},
{
"name": "Test2",
"value": "DE test2"
}
]
It has to be exact like this
{
"Test" : "EN Test",
"Test2" : "DE test2",
}
So a Single Object with the Value of all Objects of the Array but only the Values of 'name' and 'value'.
Angular merge/copy/extend and so on is working with 2 Arrays and just merging them without Options like get only value of name and value.
With Lodash
object = _.map(objectArray,'name');
Giving me
[ "Test", "Test2", ]
But with multiple
object = _.map(objectArray,['name','value']);
[ false, false, ]
doing
object = _.map(objectarray,_.partial(_.ary(_.pick,2),_,['name','value']));
output is
[ { "name": "Test", "value": "EN Test" }, { "name": "Test2", "value": "DE test2" } ]
not
{ "Test" : "EN Test", "Test2" : "DE test2", }
and so on
object = _.mapValues(objectArray,'name');
{
"0": "Test",
"1": "Values",
}
this.lang = _.mapValues(this.exportData,_.partial(_.ary(_.pick,2),_,['name','value']));
"0": {
"name": "Test",
"value": "Test"
},
"1": {
"name": "TEst2",
"value": "Test2"
},..
What can I do to achieve is
{
"Test" : "EN Test",
"Test2" : "DE test2",
}

Use native JavaScript Array#reduce method.
var data = [{
"name": "Test",
"value": "EN Test"
}, {
"name": "Test2",
"value": "DE test2"
}];
// iterate over array
var res = data.reduce(function(obj, v) {
// define the object property
obj[v.name] = v.value;
// return the object
return obj;
// define initial value as empty object
// for storing the result
}, {})
console.log(res);

Try this
var a = [
{
"name": "Test",
"value": "EN Test"
},
{
"name": "Test2",
"value": "DE test2"
}
];
var obj = {};
a.forEach(function(node){
obj[node.name] = node.value
});
console.log(obj);

Related

Groovy JsonBuilder, array inside an array

I need to build the following json using groovy's JsonBuilder().
[
{
"date": "2017-12-08",
"dog": [
{
"name": "Joe",
"age": "1"
},
{
"name": "Bro",
"age": "2"
},
{
"name": "Doe",
"age": "3"
}
]
}
]
I cant get the array in the array, because of the date, it wants to always to put date not in the same level as dog array, but put it in { }, like:
[{
{
"date": "2017-12-08",
},
"dog": [
{
"name": "Joe",
"age": "1"
},
{
"name": "Bro",
"age": "2"
},
{
"name": "Doe",
"age": "3"
}
]
}
]
Just stick the date alongside your list in the model:
import groovy.json.JsonBuilder
import groovy.transform.Canonical
#Canonical
class Dog {
int age
String name
}
#Canonical
class DogList {
String date
List<Dog> dog
}
def ark = [
new DogList('2017-12-08', [
new Dog(1, 'Joe'),
new Dog(2, 'Bro'),
new Dog(3, 'Doe')
])
]
def json = new JsonBuilder(ark).toPrettyString()
println json
prints:
[
{
"date": "2017-12-08",
"dog": [
{
"age": 1,
"name": "Joe"
},
{
"age": 2,
"name": "Bro"
},
{
"age": 3,
"name": "Doe"
}
]
}
]

Filter for array type of field in loopback

I am using loopback v3 with mongodb database and implementing filter for array type of field.
inq operator is not working.
I have an array of object like below
[
{
"name":"name1",
"title": "title1",
"category": ["a", "b","c"]
},
{
"name":"name2",
"title": "title2",
"category": ["x", "y","z"]
},
{
"name":"name3",
"title": "title3",
"category": ["b", "d","e"]
}
]
now i want a list where category containing "b"
So i am using below filter method
filter: {where:{category:{inq:["b"]}}}
I think inq does n't work for this case.it gives empty response.
Output : [ ]
how can i get my desired output.
Desired output:
[
{
"name":"name1",
"title": "title1",
"category": ["a", "b","c"]
},
{
"name":"name3",
"title": "title3",
"category": ["b", "d","e"]
}
]
below is my properties
"properties": {
"name": {
"type": "string"
},
"title": {
"type": "string"
},
"category": {
"type": [
"string"
]
}
},
Please suggest.
Thanks
for me the above scenario works fine. Although in your code the array closing brackets should be ] instead of }, just pointing out something I found in your code.
How did you setup your model for this?
"properties": {
"name": {
"type": "string"
},
"title": {
"type": "string"
},
"category": {
"type": [
"string"
]
}
},
Does your model properties look like this ?
"role": {
"type": "array",
"default": [
"patient"
]
}
let filter = {role:{in:['doctor']}}
this.find({
where: filter
}, cb);

Get dynamic key value from an array angularjs

I have a mongo collection called settings
{
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}
Note: the values provided in my mongo is only for reference purpose.
Now I have generated an array with the records in settings collection
self.sample = function() {
self.settingsObj = {}
// console.log(self.settings)
_.each(self.settings, function(settings) {
//_.each(self.settings, function(settings) {
if (!self.settingsObj[settings.type]) {
self.settingsObj[settings.type] = []
}
self.settingsObj[settings.type] = settings.list
})
console.log(self.settingsObj)
}
When I console the settingsObj I get result like this in my console
Object {subject: Array[2], exam: Array[2]}
Now I want to loop this inside a scope variable
$scope.search = [{
"name": "",
"data": ""
}]
inside this name i want to get the object name in this situation subject,exam and inside loop i want to loop the arrays for subject and exam.
I tried another ._each, and I got the key and value but how can I loop them correctly.
Otherwise please help me in generating subject and exams as different array
I'm not very sure if I understand your question.
But if I see well you're using a Lodash.js library so I provide below script using a lodash:
I assume that you have settings variable like this:
var settings = [ {
"_id": "123",
"type": "subject",
"name": "Main",
"list": [{
"_id": "123",
"name": "Maths"
}, {
"_id": "123",
"name": " Physics"
}]
}
,
{
"_id": "123",
"type": "exam",
"name": "Activities",
"list": [{
"_id": "123",
"name": "Reading"
}, {
"_id": "123",
"name": "Fluency"
}]
}];
And I create functions for process those settings:
function createSearch(settings){
return _(settings).flatMap(toSearchArray).value();
}
function toSearchArray(setting){
return _(setting.list).map("name").map(toSearchObject).value()
function toSearchObject(data){
return {
name: setting.type,
data: data
}
}
}
And when you call createSearch(settings)
you will receive this result:
[
{
"name": "subject",
"data": "Maths"
},
{
"name": "subject",
"data": " Physics"
},
{
"name": "exam",
"data": "Reading"
},
{
"name": "exam",
"data": "Fluency"
}
]
Hopefully this is what you need.

Convert the groovy map's key value pair to JSON array elements

How to take in key/value pair values of groovy map and loop into JSON array elements in groovy?.
For example:
Input:
def childmap = ["data1": "123", "data2": "234", "data3": "456"]
def childmap2= ["data4": "123", "data5": "234", "data6": "456","date7":"676"]
def parentmap= ["Key1":"Value1","Key2":"Value2","Key3":childmap,"key4":childmap2]
Expected JSON Output:
{
"Json":{
"Key1":"Value1",
"Key2":"Value2"
"key3":[
{
"Name": "data1",
"ID": "123"
},
{
"Name": "data2",
"ID": "234"
},
{
"Name": "data3",
"ID": "456"
}
],
"key4":[
{
"Name": "data4",
"ID": "123"
},
{
"Name": "data5",
"ID": "123"
},
{
"Name": "data6",
"ID": "234"
},
{
"Name": "data7",
"ID": "456"
}
]
}
}
This works for your example. This won't work if you've got deeper nesting.
def newmap = parentmap.collectEntries { key, value ->
[key, (value instanceof Map) ? value.collect {key2, value2 -> [Name: key2, ID: value2]} : value]}
def builder = new JsonBuilder([Json : newmap])
println builder.toPrettyString()

How can I get unique array from a collection of nested objects with lodash?

I have the following collection:
"items": [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Espadeiro"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [
{"description" : "Kırmızı Şaraplar Desc"},
{"region" :"Bordeaux"},
{"age": "16"},
{"producer" :"Kayra"},
{"grapeType":"Chardonnay"}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
I want to grab unique grapeTypes from that collection. The returning array shold be ["Chardonnay","Espadeiro"]
What is the best way to do it with lodash?
I think this combination of pluck, map and filter should do it:
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
console.log(result);
Check the demo run below.
// Code goes here
var obj = {
items: [{
"id": 1,
"title": "Montrachet",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Espadeiro"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999"
},
{
"id": 2,
"title": "Montrachet2",
"imageUrl": "http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"imageUrls": [
"http://winebuff.com.hk/products_image/3376-Ramonet-ChassagneMontrachetBlanc.jpg",
"http://media.riepenau.com/wines/17973_b.jpg",
"http://lorempixel.com/400/400/food/3"
],
"properties": [{
"description": "Kırmızı Şaraplar Desc"
}, {
"region": "Bordeaux"
}, {
"age": "16"
}, {
"producer": "Kayra"
}, {
"grapeType": "Chardonnay"
}
],
"priceGlass": "1",
"priceBottle": "2",
"year": "1999",
}
]
};
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return _.filter(obj, function(prop) {
return prop.grapeType;
})[0].grapeType;
}).uniq().value();
document.write(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>
UPD. If grapeType can be missing from properties then the script should be
var result = _.chain(obj.items).pluck('properties').map(function(obj) {
return (_.filter(obj, function(prop) {
return prop.grapeType;
})[0] || {}).grapeType;
}).compact().uniq().value();
Here's one way to do it with lodash:
_(items)
.pluck('properties')
.map(function(item) {
return _.find(item, _.ary(_.partialRight(_.has, 'grapeType'), 1));
})
.pluck('grapeType')
.uniq()
.value();
First, you get the properties arrays using pluck(). Next, you use find() to get the first object in this array that has a grapeType property. This is done using has(), and partially-applying the argument to build the callback function.
Next, you use pluck() again to get the actual property values. Finally, uniq() ensures there are no duplicates.

Resources