Transform flat object into array of single property objects - ecmascript-6

What is the most succinct way in ES6+ to transform this:
{
'key 1': 'value 1',
'key 2': 'value 2',
'key 3': 'value 3'
}
into this:
[
{ 'key 1': 'value 1' },
{ 'key 2': 'value 2' },
{ 'key 3': 'value 3' }
]

I would suggest using Object.entries(), then Array.Map(), along with some destructuring to transform the single object into an array of key / value pairs:
const obj = {
'key 1': 'value 1',
'key 2': 'value 2',
'key 3': 'value 3'
}
const arr = Object.entries(obj).map(([key, value]) => ({ [key]: value }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another way to approach this is simply to use Object.keys(), then accessing each value using obj[key]:
const obj = {
'key 1': 'value 1',
'key 2': 'value 2',
'key 3': 'value 3'
}
const arr = Object.keys(obj).map(key => ({ [key]: obj[key] }));
console.log('Result:', arr)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Remove empty elements from nested JSON

I have a nested json with an arbitrary depth level :
json_list = [
{
'class': 'Year 1',
'room': 'Yellow',
'students': [
{'name': 'James', 'sex': 'M', 'grades': {}},
]
},
{
'class': 'Year 2',
'info': {
'teachers': {
'math': 'Alan Turing',
'physics': []
}
},
'students': [
{ 'name': 'Tony', 'sex': 'M', 'age': ''},
{ 'name': 'Jacqueline', 'sex': 'F' },
],
'other': []
}
]
I want to remove any element that its value meet certain criteria.
For example:
values_to_drop = ({}, (), [], '', ' ')
filtered_json = clean_json(json_list, values_to_drop)
filtered_json
Expected Output of clean_json:
[
{
'class': 'Year 1',
'room': 'Yellow',
'students': [
{'name': 'James', 'sex': 'M'},
]
},
{
'class': 'Year 2',
'info': {
'teachers': {
'math': 'Alan Turing',
}
},
'students': [
{ 'name': 'Tony', 'sex': 'M'},
{ 'name': 'Jacqueline', 'sex': 'F'},
]
}
]
I thought of something like first converting the object to string using json.dumps and then looking in the string and replacing each value that meets the criteria with some kind of flag to filter it after before reading it again with json.loads but I couldn't figure it out and I don't know if this is the way to go
I managed to get the desired output by tweaking this answer a bit:
def clean_json(json_obj, values_to_drop):
if isinstance(json_obj, dict):
json_obj = {
key: clean_json(value, values_to_drop)
for key, value in json_obj.items()
if value not in values_to_drop}
elif isinstance(json_obj, list):
json_obj = [clean_json(item, values_to_drop)
for item in json_obj
if item not in values_to_drop]
return json_obj

How do i get specific value from a json data (api) using axios in vue

my json data
[ { "status": 200, "values": [ { "total_transaction": 7, "total_deposit": 4, "total_withdrawal": 3, "total_request": 4, "accepted_request": 1, "pending_request": 0 } ] } ]
my axios script
<script>
import axios from 'axios';
import dashboardData from '#/services/dashboard.service'
var dataValue = []
export default {
name: 'DashboardInfo',
data () {
return {
infoTiles: [{
color: 'success',
value: dataValue,
text: 'Total Transaction',
icon: '',
}, {
color: 'danger',
value: dataValue,
text: 'Deposit',
icon: '',
}, {
color: 'info',
value: dataValue,
text: 'Withdrawal',
icon: '',
}],
}
},
created(){
axios
.get('/dashboard')
.then(response => (response.data))
.then(result => {
dataValue.push(result)
document.getElementByName('total_transaction')
})
}
}
</script>
expectation outcome :
value : 7
text : total transaction
value : 4
text : total deposit
and so on...
for now my actual output is the json raw data with the status, values etc.
what should i code so i only get the number 7 for example instead of all of the data.
i know what iam doing is wrong since im really a beginner in this matter and its my first app i made using axios-vue.
As I assumed, your json data is always like this.
[ { "status": 200, "values": [ { "total_transaction": 7, "total_deposit": 4, "total_withdrawal": 3, "total_request": 4, "accepted_request": 1, "pending_request": 0 } ] } ]
you have to modify your code on axios response. The code may solve your problem.
import axios from 'axios';
import dashboardData from '#/services/dashboard.service'
var dataValue = []
export default {
name: 'DashboardInfo',
data () {
return {
infoTiles: [{
color: 'success',
value: 0,
text: 'Total Transaction',
icon: '',
}, {
color: 'danger',
value: 0,
text: 'Total Deposit',
icon: '',
}, {
color: 'info',
value: 0,
text: 'Total Withdrawal',
icon: '',
}, {
color: 'info',
value: 0,
text: 'Total Request',
icon: '',
}, {
color: 'info',
value: 0,
text: 'Accepted Request',
icon: '',
}, {
color: 'info',
value: 0,
text: 'Pending Request',
icon: '',
}],
}
},
created(){
var that = this;
axios
.get('/dashboard')
.then(response => (response.data))
.then(result => {
var values = result.data.values;
var infoTiles = that.infoTiles;
infoTiles[0].value = values['total_transaction'] ? values['total_transaction'] : 0;
infoTiles[1].value = values['total_deposit'] ? values['total_deposit'] : 0;
infoTiles[2].value = values['total_withdrawal'] ? values['total_withdrawal'] : 0;
infoTiles[3].value = values['total_request'] ? values['total_request'] : 0;
infoTiles[4].value = values['accepted_request'] ? values['accepted_request'] : 0;
infoTiles[5].value = values['pending_request'] ? values['pending_request'] : 0;
that.$set(that, 'infoTiles', infoTiles);
})
}
}
Alright i kinda found a way around this.
this is what i did
mounted(){
axios
.get('/dashboard')
.then(response => (response.data.values[0].total_transaction))
.then(result => {
dataValue.push(result)
})
output i get
[7]
total transaction
i just have to push every response to a single var dedicated for each object.
i know its not the most effective way to do it, but it works

How to use React-widget Dropdownlist with groupby attribute

I need to use react-widgets dropdownlist with groupby attribute.
A typical example of this would be;
<Multiselect
data=[{name:'Dan' lastName:'Black'}, {name:'Man' lastName:'Black'}]
textField='name'
groupBy='lastName'
/>
But the data array i have of is of a completely different structure. like;
[
{
name:'test one',
objects: [{key:'my key', value:'my value'},
{key:'my key1', value:'my value1'}
{key:'my key2', value:'my value2'}]
},
{
name:'test two',
objects: [{key:'my key', value:'my value'},
{key:'my key1', value:'my value1'}
{key:'my key2', value:'my value2'}]
}
]
And i need the 'key' to be the value displayed in the list and groupby on 'name'.
Is this possible to achieve or just completely stupid and i have to restructure it totally?
Each objects array is honestly 100 or more objects long.. so i prefer not to restructure it again due to performance issue.
Thanks in advance, All ideas are welcome!
UPDATE:
<DropdownList
data = {
[{
repoName: 'google repository',
objects: [
{
key: 'mykey',
method: 'my meth',
value: 'my val'
},
{
key: 'mykey2',
method: 'my meth2',
value: 'my val2'
}]
}]}
textField='objects.key'
placeholder={placeholder}
groupBy='repoName'
/>
Gives something like;
google repository
[Object Object]
How could iterate that object array to avoid this?
According to my understanding, what you can do is create a different structure for data using your existing one.
const data = [{
name: 'test one',
objects: [{
key: 'my key',
value: 'my value'
}, {
key: 'my key1',
value: 'my value1'
} {
key: 'my key2',
value: 'my value2'
}]
}, {
name: 'test two',
objects: [{
key: 'my key',
value: 'my value'
}, {
key: 'my key1',
value: 'my value1'
} {
key: 'my key2',
value: 'my value2'
}]
}]
const newData = []
data.forEach((element) => {
const name = element.name
if (element.objects && element.object.length) {
element.objects.forEach((keyValueData) => {
newData.push({
name,
key: keyValueData.key,
value: keyValueData.value,
})
})
}
})
< Multiselect
data = {
newData
}
textField = 'name'
groupBy = 'key' / >
This way, it should solve your issue.Mind brackets not tested the code

How to delete an object from a json in angular 2 and ionic

export default [
{
user:{
id: '1',
person: 'Theodore Roosevelt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
},
{
user:{
id: '2',
person: 'Normale',
text: 'Change your thoughts and you change your world.',
icon:'woman'
}
}, {
user:{
id: '3',
person: 'Thlt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
}]
The code above is a ts file under data folder in ionic tool.
I wish to delete an entry from this array on basis of id by click of delete button in front of each entry.
I'm new to ionic . I tried .slice it didn't work
const arr = [{
user:{
id: '1',
person: 'Theodore Roosevelt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
},
{
user:{
id: '2',
person: 'Normale',
text: 'Change your thoughts and you change your world.',
icon:'woman'
}
}, {
user:{
id: '3',
person: 'Thlt',
text: 'Believe you can and you\'re halfway there',
icon:'man'
}
}]
const id = '2'; // 2 will be removed
const result = arr.filter(item => (item.user || {}).id !== id)
console.log(result)

Using filter with each on lodash

I have this JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
},
{
uri : '/someuri/three',
title : 'Title 3',
displayLocation : 'ACTION_MENU',
masterData : 'JOB',
iconClass : 'icon-class-3'
},
{
uri : '/someuri/four',
title : 'Title 4',
displayLocation : 'SUMMARY',
masterData : 'LOCATION',
iconClass : 'icon-class-4'
}
]
I am converting it to
[
{
iconClass : 'icon-class-1',
id : 'anythingUnique',
text : 'Title 1'
},
{
iconClass : 'icon-class-2',
id : 'anythingUnique',
text : 'Title 2'
}
]
using following code
function myCustomFilter(inputJSONStr) {
return _.each(inputJSONStr.filter(function(action){
return action.masterData === 'LOCATION' && action.displayLocation === 'ACTION_MENU';
}), function (action) {
return [{iconClass: action.iconClass, id: 'anythingUnique', text: action.title}];
});
But its returning me JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
}
]
Can anyone suggest what I am doing wrong?
You could use map to do this:
_(inputJSONStr).filter({masterData: 'LOCATION', displayLocation: 'ACTION_MENU'})
.map(function(a) {
return {iconClass: a.iconClass, id: 'anythingUnique', text: a.title};
}).value();
I've changed your filter a little, but you could do it your way if you wanted, and I've used a functional approach with chaining, but you could do it imperatively if that makes you more comfortable. Map effectively replaces an array element with the returned element.