I got problem, I've array of string as
[
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
I need to convert it to Object
[
{"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
{}
]
likewise.
JSON.parse won't work on non-serialized string.
Using Object.fromEntries()
var data = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
var result = data.map(v =>
Object.fromEntries(v.split(',').map(v => v.split(/:(.*)/)))
)
console.log(result)
Something like this should work:
input.map(v => v.split(',').map(v => {
const [key, ...value] = v.split(':');
const obj = {};
obj[key] = value.join(':');
return obj;
}))
You can get it using map and reduce:
const arr = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
const newArr = arr.map(item => {
return item.split(",").reduce((acc, curr) => {
const label = curr.split(":")[0];
const value = curr.substring(label.length+1)
acc[curr.split(":")[0]] = value
return acc;
},{})
})
console.log(newArr)
You have to split your strings by commas and colons. Only problem is that your time string has a bunch of colons in it. Here is a start.
var a = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
];
b = a.map(function(line) {
var obj = {};
line.split(",").forEach(function(item) {
kv = item.split(/:(.+)/,2);
obj[kv[0]]=kv[1];
});
return obj;
});
console.log(b);
Related
How can I loop through this array:
const counts = [
"900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk",
];
taking each value from this array?
const uniqueDomains = [
'google.com',
'com',
'mail.yahoo.com',
'yahoo.com',
'mobile.sports.yahoo.com',
'sports.yahoo.com',
'stackoverflow.com',
'overflow.com',
'com.com',
'en.wikipedia.org',
'wikipedia.org',
'org',
'm.wikipedia.org',
'mobile.sports',
'sports',
'google.co.uk',
'co.uk',
'uk'
]
I need to find out if string from counts array includes string from uniqueDomains array.
Then push it to the empty object as a key value pairs, where value
is going to be the number in the beginning of the each string from counts array.
I tried this code but it give me wrong result in my object's values(since I am looping twice)
I need kind of avoid looping twice, but I am not sure how.
Example com is mentioned 8 time in counts array, which means result should be this {com: 1345}
Here is my code:
const finalObject = {}
uniqueDomains.forEach((dom) => {
counts.forEach((cnt) => {
if (cnt.includes(dom)) {
const num = parseInt(cnt);
sumArr.push(num);
const res = sumArr.reduce((acc, cur) => {
return acc + cur;
});
finalObject[dom] = res;
}
});
});
Theres not really any avoiding looping twice (at least), but you can certainly make your code a bit easieer by first turning the count array into an array of val & domain separately.
const countIdx = counts.map(x => {
const [val,domain] = x.split(",");
return {val:parseInt(val,10), domain}
});
Then its just a case of looping the uniqueDomain array and finding all the domaion which match and summing up the val
const result = uniqueDomains.reduce( (res, d) => {
const count = countIdx.filter(x => x.domain.includes(d)).reduce( (acc,x) => acc + x.val,0);
return {...res, [d]:count}
},{});
Live example follows:
const counts = [
"900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk",
];
const uniqueDomains = [
'google.com',
'com',
'mail.yahoo.com',
'yahoo.com',
'mobile.sports.yahoo.com',
'sports.yahoo.com',
'stackoverflow.com',
'overflow.com',
'com.com',
'en.wikipedia.org',
'wikipedia.org',
'org',
'm.wikipedia.org',
'mobile.sports',
'sports',
'google.co.uk',
'co.uk',
'uk'
]
const countIdx = counts.map(x => {
const [val,domain] = x.split(",");
return {val:parseInt(val,10), domain}
});
const result = uniqueDomains.reduce( (res, d) => {
const count = countIdx.filter(x => x.domain.includes(d)).reduce( (acc,x) => acc + x.val,0);
return {...res, [d]:count}
},{});
console.log(result);
Maybe try something like:
let finalObject = {}
uniqueDomains.forEach((dom) => {
finalObject[dom] = 0;
counts.forEach((cnt) => {
if (cnt.includes(dom)) {
finalObject[dom] += parseInt(cnt);
}
});
});
const obj = {
obj_abc: '',
obj_def: '',
hello_123: '',
hello_456: ''
}
If I have an object that its property has a certain pattern of prefix how can I split them into multiple arrays?
like
const arr1 = [{
obj_abc: '',
obj_def: ''
}]
const arr2 = [{
hello_123: '',
hello_456: ''
}]
I couldn't think of a way that I can partially match the properties of an object.
My version using Object.keys
const obj = {
obj_abc: 1,
obj_def: 2,
hello_123: 3,
hello_456: 4,
}
const arr1 = [];
const arr2 = [];
Object.keys(obj).forEach(key => {
if (key.match(/hello_.*/)) {
arr1.push({
[key]: obj[key]
});
} else {
arr2.push({
[key]: obj[key]
});
}
});
console.log(arr1, arr2);
You could use reduce method on Object.entries and return one object with separate properties for each similar keys. This assumes you want to match part of the key before _
const obj = {
obj_abc: true,
obj_def: true,
hello_123: true,
hello_456: true
}
const result = Object.entries(obj).reduce((r, [k, v]) => {
const [key] = k.split('_');
if (!r[key]) r[key] = {}
r[key][k] = v
return r;
}, {})
const [r1, r2] = Object.values(result)
console.log(r1)
console.log(r2)
Simplest answer using plain javascript
const a = {
obj_abc:123,
obj_def:456,
hello_123: 123,
hello_456:456
};
const b = {};
for(k in a){
const [key] = k.split('_');
if(!b[key]) {
b[key] = [];
}
b[key].push(a[k]);
}
console.log(b);
I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);
I would like to know how would I merge this bidimensional array
let arr[
['Reference', 'Price'],
['232323DD, 15.00]
];
I want to convert this into
[
{name: 'Reference', value: '232323DD'},
{name: 'Price', value: 15.00}
]
I've tried this:
Convert a two dimensional array into an array of objects
but It didn't work for me.
You can use .map():
let [keys, values] = [
['Reference', 'Price'],
['232323DD', 15.00]
];
let result = keys.map((k, i) => ({name: k, value: values[i]}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can map through the first array in that array and use their values as the keys to an object:
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
console.log(
arr[0].map((name, i) => ({name, value:arr[1][i]}))
)
If you are unsure about the size of the two arrays, you should first check whether their lengths are equal, to avoid undefined.
Other solution if you are not familiar with map (I think using map for this example make it a bit hard to read)...
const arr = [
['Reference', 'Price'],
['232323DD', 15.00]
]
const obj = []
arr.forEach(x => obj.push({name: x[0], value: x[1]}))
console.log(obj)
You can use the map function. It will run the callback on each array item, return it in a new array.
// where 'arr' is your original array
const new_arr = arr.map((item) => {
// this is called a 'destructuring assignment'
const [name, value] = item;
// return the values as fields in an object
return {name, value};
});
const arrArr = [['Reference', 'Price'], ['232323DD, 15.00]];
const objArr = [];
for (const item of arrArr) {
objArr.push({name: item[0], value: item[1]});
}
let arr = [
['Reference', 'Price'],
['232323DD', '15.00']
];
let result = arr[0].map((key, i) => ({name: key, value: arr[1] ? arr[1][i] : null}));
console.log(result);
I'll try to break this down:
// 1. create a new arr object:
let convertedArr = [];
// 2. loop over the original array:
for(let i = 0; i < arr.length; i++){
let currentItem = arr[i];
//create a temp object
let obj = {name:currentItem[0], value: name:currentItem[1] };
//push a new object to the array
convertedArr.push(obj);
}
I have an array like that
I want to pick the array item by property name, I am using lodash for that:
const result = _.map(this.thing, _.property('groups')).filter(x => x !== undefined);
But I am getting array of arrays as result
What I need is just single selected property array.
Any idea how to achieve that?
Try this>>>
var a = [{"p1":[3,4]},{"p2":[6,7]}];
function getArr(arr,key){
var res = [];
for(var v of arr){
if(v[key]!=undefined){
res = v[key];break;
}
};
return res;
}
console.log(getArr(a,"p1"));
If you can use ES6/ES7, you can rely on Object.keys and Object.values to access to the key (that is the property name) and the value (the array you want to get):
var arr = [
{ groups: [1, 2 ] },
{ category: [1, 2, 3 ] },
{ subCategory: [1, 2, 3, 4 ] }
];
function pickArray(propertyName) {
var element = arr.find(el => Object.keys(el)[0] === propertyName)
return element ? Object.values(element)[0] : null;
}
var res = pickArray('category');
console.log(res);
const output
= (Array.from(arr, (obj) => obj['product'], 'product')
.filter(x => typeof x !== 'undefined'))[0];
Try this:
const arr = [ {'groups': ['item1','item2']},
{'categories':['x','y']}
]
var ouptut= arr.find(item=> {
return item[Object.keys(item).find(key=>key === 'groups')]
})
console.log(ouptut)