combining a names array with the values array in object es6 - javascript

I'm using the influxdata API and that data comes back in this format:
{
"columns": [
"time",
"commit_time",
"expiration_time",
"kafka_consumer_group",
"kafka_offset_group",
"kafka_topic",
"kafka_topic_parition",
"message_metadata"
],
"name": "offsets",
"values": [
[
"2017-04-01T22:51:50.301Z",
"1491087110301",
"1491173510301",
"group-general-service-master",
0,
"replica-conversion-dev",
"6",
"NO_METADATA"
],
[
"2017-04-01T22:51:50.301Z",
"1491087110301",
"1491173510301",
"group-message-service-master",
2,
"service-dev",
"4",
"NO_METADATA"
],
[
"2017-04-01T22:51:50.303Z",
"1491087110303",
"1491173510303",
"group-general-service-mk-threadc",
7073,
"posted-dev",
"1",
"NO_METADATA"
]
]
}
The columns and values are separate but how can I combine the columns and values arrays together so that the values have the names with them:
{
[
{
"time": "2017-04-01T22:51:50.301Z",
"commit_time": "1491087110301",
"expiration_time": "1491173510301",
"kafka_consumer_group": "group-general-service-master",
"kafka_offset_group": 0,
"kafka_topic": "replica-conversion-dev",
"kafka_topic_partition": "6",
"message_metadata": "NO_METADATA"
}
]...
}

Your desired result is not a valid object/array notation.
Assuming you would like to get an array of object, you can try the following:
res.values.map(arr => ({
time: arr[0],
commit_time: arr[1],
expiration: arr[2],
// you get the idea...
}));
Or using array destructuring:
res.values.map(arr => {
var obj = {};
[
obj.time,
obj.commit_time,
obj.expiration,
// you get the idea...
] = arr;
return obj;
});

Assuming you need an array of objects, you could iterate the values array and for the keys the columns array and assign the objects to the collecting object. Then return a new array with the objects.
var data = { columns: ["time", "commit_time", "expiration_time", "kafka_consumer_group", "kafka_offset_group", "kafka_topic", "kafka_topic_parition", "message_metadata"], name: "offsets", values: [["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-general-service-master", 0, "replica-conversion-dev", "6", "NO_METADATA"], ["2017-04-01T22:51:50.301Z", "1491087110301", "1491173510301", "group-message-service-master", 2, "service-dev", "4", "NO_METADATA"], ["2017-04-01T22:51:50.303Z", "1491087110303", "1491173510303", "group-general-service-mk-threadc", 7073, "posted-dev", "1", "NO_METADATA"]] },
result = data.values.map(a => Object.assign({}, ...data.columns.map((k, i) => ({ [k]: a[i] }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

ReactJS - Filter Nested Array of Objects

So I am trying to set up a filter on nested array of objects. The thing is the filter is object.
I just got the empty result.
Data sample:
obj:[
{
"success": true,
"data": {
"purpose": {
"label": "Purpose",
"type": "choice",
"value": {
"select": "loremIpsum",
"options": [
{
"value": "loremIpsum",
"text": "loremIpsum"
}
]
},
"filter_groups": [
"sd",
"coll"
],
"checklist_groups": {
"sd": {
"value": null,
"comment": [],
"is_disabled": false
}
}
},
"description": {
"label": "Description",
"type": "choice",
"value": {
"select": "loremIpsum",
"options": [
{
"value": "loremIpsum",
"text": "loremIpsum"
}
]
},
"filter_groups": [
"dv"
],
"checklist_groups": {
"sd": {
"value": null,
"comment": [],
"is_disabled": false
}
}
}
}
}
]
Try to do next:
const filterData = (e) => {
let filtredData = Object.entries(obj)
.map(item => ({
...item,
filter_groups: item.filter_groups
.filter(child => child === e)
}))
return filtredData;
}
But filter wants work, how filter by nested objects?
I want to filter by filter_groups.
Do I have to use a regex to define the filter?
It's really not entirely clear what exactly you want as input and how your output should be formatted. This version assumes you just want the data property of the first value of obj's array, and turns it back into an object with the same sorts of keys you had in the original (such as "purpose" or "description").
const filterData = (e) => (data) => Object .fromEntries (
Object .entries (data) .filter (([k, {filter_groups}]) => filter_groups .includes (e))
)
const obj = [{success: !0, data: {purpose: {label: "Purpose", type: "choice", value: {select: "loremIpsum", options: [{value: "loremIpsum", text: "loremIpsum"}]}, filter_groups: ["sd", "coll"], checklist_groups: {sd: {value: null, comment: [], is_disabled: !1}}}, description: {label: "Description", type: "choice", value: {select: "loremIpsum", options: [{value: "loremIpsum", text: "loremIpsum"}]}, filter_groups: ["dv"], checklist_groups: {sd: {value: null, comment: [], is_disabled: !1}}}}}]
console .log ('"sd": ', filterData ('sd') (obj [0] .data))
console .log ('"dv": ', filterData ('dv') (obj [0] .data))
console .log ('"foobar": ', filterData ('foobar') (obj [0] .data))
.as-console-wrapper {max-height: 100% !important; top: 0}
Forgetting that outer shell, the trick here is that we convert it to an array of key-value entries with Object .entries, filter those entries by whether the filter_groups property of the value contains our target value, and convert the resulting array of entries back into an object.
Try using a predicate method to perform a boolean test and determine it obj:[] is behaving live an array
```Array.isArray(arr); // true ```

How to merge objects and append it into new array if object values are same using JavaScript?

I have this kind of data, my goal is to find all same request_id values in the given objects, merge it to one object and append its unique_id into one array, How can I get this result?
let fakeData = {
"622b1e4a8c73d4742a66434e212":{
request_id: "1",
uique_id:'001'
},
"622b1e4a8c73d4742a6643423e54":{
request_id: "1",
uique_id:'002'
},
"622b1e4a8c73d4742a6643423e23":{
request_id: "2",
uique_id:'003'
},
}
let parts = []
for (const property in fakeData) {
console.log(fakeData[property]);
}
//Result should be
// [{request_id:'1', values:["001, 002"]}, {request_id:'2', values:["003"]}]
You can iterate over all the values using Object.values() and array#reduce. In the array#reduce group based on request_id in an object and extract all the values of these object using Object.values().
const fakeData = { "622b1e4a8c73d4742a66434e212": { request_id: "1", uique_id: '001' }, "622b1e4a8c73d4742a6643423e54": { request_id: "1", uique_id: '002' }, "622b1e4a8c73d4742a6643423e23": { request_id: "2", uique_id: '003' }, },
output = Object.values(fakeData).reduce((r, {request_id, uique_id}) => {
r[request_id] ??= {request_id, values: []};
r[request_id].values.push(uique_id);
return r;
},{}),
result = Object.values(output);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

array of arrays conversion in Javascript

I need to create an array of array.
It is worth noting that the database is very large and that if any attribute does not have a corresponding value, it sends an empty string. I've tried with map and reduce but I wasn't successful:
Any help will be appreciated.
Below I show an example of the expected output:
outputExpected = [
["id", 1, 2],
["name", "name1", "name2"],
["price", 6.95, 998.95],
["promoPrice", 5.91, 333.91],
["category", "test1 | test2", "test3 | test4"],
]
Any way to solve this problem performatically?
this is my code:
let arrayObj = [{
"id": 1,
"name": "name1",
"price": 6.95,
"promoPrice": 5.91,
"category": ["test1, test2"]
},
{
"id": 2,
"name": "name2",
"price": 998.95,
"promoPrice": 333.91,
"category": ["test3, test4"]
}
]
const headers = ["id", "name", "price", "promoPrice", "category"]
const result1 = headers.concat(arrayObj.map((obj) => {
return headers.reduce((arr, key) => {
arr.push(obj[key]) return arr;
}, [])
}))
console.log(result1)
Reduce the array to a Map. On each iteration convert the object to an array of [key, value] pairs using Object.entries(). Use Array.forEach() to iterate the entries and add them to the map. Convert the Map's values iterator to an array using Array.from():
const arr = [{"id":1,"name":"name1","price":6.95,"promoPrice":5.91,"category":["test1", "test2"]},{"id":2,"name":"name2","price":998.95,"promoPrice":333.91,"category":["test3", "test4"]}]
const result = Array.from(arr.reduce((acc, o) => {
Object.entries(o)
.forEach(([k, v]) => {
if(!acc.has(k)) acc.set(k, [k])
acc.get(k).push(Array.isArray(v) ? v.join(' | ') : v)
})
return acc
}, new Map()).values())
console.log(result)
You could simply map the value and check if an item is an array, then take the joined values or the value itself.
const
data = [{ id: 1, name: "name1", price: 6.95, promoPrice: 5.91, category: ["test1, test2"] }, { id: 2, name: "name2", price: 998.95, promoPrice: 333.91, category: ["test3, test4"] }],
headers = ["id", "name", "price", "promoPrice", "category"],
result = data
.reduce(
(r, o) => headers.map((k, i) => [
...r[i],
Array.isArray(o[k]) ? o[k].join(' | ') : o[k]
]),
headers.map(k => [k]),
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
construct one init array with all possible keys with the wanted order, then uses Array.reduce and Array.forEach to Array.push value for per key based on its index.
const arrayObj = [
{
"id":1,
"name":"name1",
"price":6.95,
"promoPrice":5.91,
"category":["test1", "test2"]
},
{
"id":2,
"name":"name2",
"price":998.95,
"promoPrice":333.91,
"category":["test3", "test4"]
}
]
function ConvertToArray2D (items) {
let init = [['id'], ['name'], ['price'], ['promoPrice'], ['category']]
if (!items) return init
return arrayObj.reduce((pre, cur) => {
init.forEach((key, index) => {
pre[index].push(Array.isArray(cur[key[0]]) ? cur[key[0]].join('|') : cur[key[0]])
})
return pre
}, init.slice())
}
console.log(ConvertToArray2D(arrayObj))
This can be handled with a standard 'zip' after mapping your objects to arrays of values in line with the headers array. (This also allows for the result to be pivoted back).
//** #see https://stackoverflow.com/a/10284006/13762301
const zip = (...rs) => [...rs[0]].map((_, c) => rs.map((r) => r[c]));
const headers = ['id', 'name', 'price', 'promoPrice', 'category'];
const arrayObj = [{ id: 1, name: 'name1', price: 6.95, promoPrice: 5.91, category: ['test1', 'test2'] },{ id: 2, name: 'name2', price: 998.95, promoPrice: 333.91, category: ['test3', 'test4'] },];
const result = zip(
headers,
...arrayObj.map((o) => headers.map(h => Array.isArray(o[h]) ? o[h].join(' | ') : o[h]))
);
console.log(result);
// which also allows it to be reversed
console.log(zip(...result));
.as-console-wrapper { max-height: 100% !important; top: 0; }
see: Javascript equivalent of Python's zip function for further zip discussion.

Find nested arrays based on inner array length

I'm currently working with an array of nested arrays and attempting to pull out certain arrays if they meet a condition (length greater than 1). Here's the array -
const testArr = [
{
"type": 1,
"categories": [
{
"description": "Foo",
"subOptions": [
{
"subType": 1,
"subTypeTypeDescription": "Bar"
}
],
}
]
},
{
"type": 2,
"categories": [
{
"description": "Baz",
"subOptions": [
{
"subType": 2,
"subTypeTypeDescription": "Baf"
},
{
"subType": 3,
"subTypeTypeDescription": "Bee"
}
],
}
]
}
]
What I'm hoping to produce is an array of categories, but only if those categories have a subOptions array with a length > 1. Here is the hoped for result on the array above -
[
{
"description": "Baz",
"subOptions": [
{
"subType": 2,
"subTypeTypeDescription": "Baf"
},
{
"subType": 3,
"subTypeTypeDescription": "Bee"
}
],
}
]
I can get this to work by using normal foreach loops like so -
let categories: [];
testArr.forEach((service) => {
service.categories.forEach((cat) => {
if(cat.subOptions.length > 1) {
categories.push(cat)
}
})
})
but I'm trying to learn how to do these things with functional tools. I've tried to do it now several times with a mix of map, filter, and reduce and keep failing. If anyone can offer some direction on the most optimal way to do the same thing with functional methods, I'd greatly appreciate it.
Use a .filter that checks the length of the sub-array:
const testArr=[{type:1,categories:[{description:"Foo",subOptions:[{subType:1,subTypeTypeDescription:"Bar"}]}]},{type:2,categories:[{description:"Baz",subOptions:[{subType:2,subTypeTypeDescription:"Baf"},{subType:3,subTypeTypeDescription:"Bee"}]}]}];
const result = testArr
.flatMap(item => item.categories)
.filter(({ subOptions }) => subOptions.length >= 2);
console.log(result);
Try this
const categories = testArr.map(service => {
return service.categories.filter(category => category.subOptions.length > 1);
})
Or even this in one line:
const categories = testArr.map(service => service.categories.filter(category => category.subOptions.length > 1));

How to merge multiple json arrays into one array swift sub array in Javascript?

I have two json arrays :
1)
[
{
"userId": 9
},
{
"userId": 14
}
]
2)
[{"role": "1", "group": "3"}, {"role": "1", "group": "2"}]
I would like to merge two arrays like as follows :
Is it possible to have the solution by javascript?
[
{"userId":9,"role":"1","group":"2"},
{"userId":14,"role":"1","group":"2"}
{"userId":9,"role":"1","group":"3"},
{"userId":14,"role":"1","group":"3"}
]
I tried to use Let however I couldn't find the way to manipulate switch the subarray :
let arr1 =
[{ "userId": 9 }, { "userId": 14 }]
let arr2 = [{"role": "1","group": "3"}, {"role": "1","group": "2" }]
let result = arr1.map(o => Object.assign(o, ...arr2));
console.log(result);
return result;
The result is like this :
[{"userId":9,"role":"1","group":"2"},{"userId":14,"role":"1","group":"2"}]
Thanks in advance.
You can use .map() with Object.assign():
let arr1 = [{"userId": 9}, {"userId": 14}],
arr2 = [{"rid": 1}, {"mid": 201}];
let result = arr1.map(o => Object.assign(o, ...arr2));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
#Mohammad Usman has a better answer but one simpler to understand is to create a new object with the desired values and push it into the resulting array. Something as follows:
users = [
{"userId": 9},
{"userId": 14}
];
data = [
{"rid": 1},
{"mid": 201}
];
result = [];
for (var i = 0; i < users.length; i++) {
result.push({
"rid": data[0].rid,
"mid": data[1].mid,
"userId": users[i].userId
});
}
Here result will have the desired output.

Categories