I have a JSON array that looks like this:
[{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}]
I would like to transform the above into the following
[{
label: 'all',
data: [3,2,3]
},
{
label: 'monday',
data: [2,2,2]
}]
Thanks in advance
Given input:
const input = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
Looks like the semantics of what you want to do align very well with Array.map.
For each values in the input array, map it to an object such that label is set by day (key rename), and put in to data the values of the other entries.
To get the entries (key,value pairs) we use Object.entries. We Array.filter to get those with key !== 'day'. We want an array of the values, so we map the filtered entries (key,value pairs) to only the values. The input is string, but looks like you want it as numbers, so we convert using Number function
const output = input.map(obj => ({
label: obj.day,
data: Object.entries(obj).filter(([key]) => key !== 'day').map(([, val]) => Number(val)),
}));
In one line of code:
arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})):
looping over array and getting the day using Destructuring from object and clients using rest_parameters
let arr = [{
"day":"all",
"client_first":"3",
"client_second":"2",
"client_third":"3"
},
{
"day":"monday",
"client_first":"2",
"client_second":"2",
"client_third":"2"
}];
console.log(arr.map(({day,...clients})=>({label:day,data:[Object.values(clients).map(Number)]})))
Related
The objects are pulled from the backend, the objects can be different lengths and can contain different values.
I want to custom sort these objects in this order of the array below:
let array = ["packhouse", "location", "date", "time"]
this is what I can do (searching through the web):
var myArray = [{
name: 'packhouse'
},
{
name: 'notPackhouse',
date: "date"
},
{
name: 'a'
},
];
myArray.sort(function(a, b) {
return array.indexOf(a.name) - sortOrder.indexOf(b.name);
});
the data being pulled doesnt always have "packhouse" or could be a bigger length than the custom order array. is there a better solution for this?
I have an array containing objects that every element but the last one are objects, but I want to convert them into an array of arrays and add the last element.
To be more explicit here is how I have it:
[
{ 0: [1,2], 1: [6,2], name: "" },
{ 0: [3,4], 1: [2,2], name: "" }
]
and the result I want is this one:
[
{ multipolygon: [ [1,2], [6,2] ], name: ""},
{ multipolygon: [ [3,4], [2,2] ], name: ""}
]
Each single array contained inside the original array is converted into an array of those arrays.
I have tried doing this:
const zonesArray = zones.map(el => Object.values(el)) // obj => array
const polygons = zonesArray.filter(el => el.pop()) // array without name
to get all the arrays contained inside the obj but then I realized how can I replace this into the original objects.
I have tried to modify the groupBy function found on MDN:
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
acc[key].push(obj)
return acc
}, {})
}
But I can't seem to find the answer
It doesn't look like you're trying to group by a property, you're trying to transform each object in the array separately - which can be done by taking the name and the numeric properties together when mapping, then returning the shape of the new object:
const arr = [
{ 0: [1,2], 1: [6,2], name: "" },
{ 0: [3,4], 1: [2,2], name: "" }
];
const result = arr.map(({ name, ...rest }) => ({
name,
multipolygon: Object.values(rest)
}));
console.log(result);
I have the following structure and this data is displaying as the list in (as in my given screenshot), here I want to add a filter, like say If I put "a" in my search box it should display all the names which has "a" and when I type the full name like "atewart Bower" it should only show the one list. So far I doing this
const searchContact = newData.filter(d => { // here newData is my arr of objs
let alphabet = d.alpha.toLowerCase();
return alphabet.includes(this.state.searchUserName.toLowerCase())
})
it is returning on the basis of "alpha" not "name" inside the users array. I was trying to use Lodash and underscore.js, but didn't find what I want to achieve there too.
I tried this code of Lodash
const dd = _.filter(newData, { users: [ { name: this.state.searchUserName } ]});
but it also return the array of object when I write the full name like when this.state.searchUserName = atewart Bower
[
{
alpha: "a",
users: [
{
id: "1",
name: "atewart Bower"
},
{
id: "1",
name: "aatewart Bower"
},
]
},
{
alpha: "b",
users: [
{
id: "1",
name: "btewart Bower"
},
{
id: "1",
name: "bbtewart Bower"
},
]
}
]
It is filtering on basis of alpha because inside the filter, we are using alpha value to check.
let alphabet = d.alpha.toLowerCase();
return alphabet.includes(this.state.searchUserName.toLowerCase())
To check inside the users array, you can do something like this
const getSearchedContacts = (newData, searchUserName) => {
const searchResults = [];
newData.forEach((item) => {
const users = item.users.filter(user => user.name.toLowerCase().startsWith(searchUserName.toLowerCase()));
if (users.length) searchResults.push({...item, users});
});
return searchResults;
};
getSearchedContacts(yourData, 'atewart Bower'); // Returns [{"alpha":"a","users":[{"id":"1","name":"atewart Bower"}]}]
Note: I'm using startsWith instead of includes because we want to return only one name when search string is for example "atewart Bower"
I'm learning to manipulate JSON data and I am stuck trying to figure out how to cajole the following JSON into what I want as shown below:
Any pointers to function/terms/concepts that I should learn for this sort of problem would be greatly appreciated! Thanks
JSON object
{
car: 1,
van: 5,
cat: 99999999999999999999999
}
Desired outcome:
items: [
{ "type": "car", "value": "1"},
{ "type": "van", "value": "5"},
{ "type": "cat", "value": "99999999999999999999999"}
]
You can use a combination of Object.entries and Array.prototype.map:
const obj = { car: 1, van: 5, cat: 99999999999999999999999 };
let list = Object.entries(obj) // [["car",1],["van",5],["cat",99999999999999999999999]]
.map(x => ({ type: x[0], value: x[1] }));
console.log(list);
Or, with some destructuring:
const obj = { car: 1, van: 5, cat: 99999999999999999999999 };
let list = Object.entries(obj)
.map(([type, value]) => ({ type, value }));
console.log(list);
The callback to map:
([type, value]) => ({ type, value })
Expects an array as parameter: [type, value]. The first value in that array is assigned to type, the second one to value.
Then we use a shorthand form to set these values in our returned object:
=> ({ type, value })
I'm a beginner. I tried to solve the problem and this is the best I can come up with, tested in Node.js 10.
const obj = {"car": 1, "van": 5, "cat": 999999}
const items = []
for (let key in obj) {
items.push({"type": key, "value": obj[key]})
}
console.log(items)
One thing I am slightly confused about is the difference between for..in vs for..of, I'm currently looking into it.
Object.keys will return:
['car', 'van', 'cat'];
On this array you can use Array's map function which creates a new array with the results of calling a provided function on every element in the calling array.
var a = {
car: 1,
van: 5,
cat: 99999999999999999999999
}
m = Object.keys(a).map((v)=>{
return {
type: v,
value: a[v]
}
})
console.log(m);
#GustavMahler hope you understand. To learn more about array functions you should look map, reduce and filter.
This one uses object.keys
let js = {car:1, van:5, cat:9999}
Object.keys(js).map( x => ({type: x, value: js[x] }) )
[ { type: 'car', value: 1 },
{ type: 'van', value: 5 },
{ type: 'cat', value: 9999 } ]
I have this array of objects
[ { id: '573267d06b2957ab24c54d59' },
{ id: '573267d06b2957ab24c54d5a' },
{ id: '573267d06b2957ab24c54d5b' },
{ id: '573267d06b2957ab24c54d5c' },
{ id: '573267d06b2957ab24c54d5d' }
]
I wish to convert it to the following in NodeJs
[ '573267d06b2957ab24c54d59',
'573267d06b2957ab24c54d5a',
'573267d06b2957ab24c54d5b',
'573267d06b2957ab24c54d5c',
'573267d06b2957ab24c54d5d'
]
It seems like it should be easy given the right library/package, but I am struggling to find the right wording to "flatten" the array into the IDs of the contained objects.
Say your array of objects is called arr, just do this:
var arrayOfStrings = arr.map(function(obj) {
return obj.id;
});
map will iterate over the array and create a new array based on how you define your function. In this case we return the value of the id key in each case to build out the desired array of ids.