Java script key value pair to object - javascript

I am new to javascript. I have an array of data in the format:
Toronto, Ontario: 95
Markham, Ontario: 71
I want to convert it to an array of object:
Like this, to be consistent with other functions.
I tried:
reportData.fbcity = Object.keys(reportData.city).map((city) => {
return {
city: city,
value: reportData.city[city]
};
});
What I get is:
{city: "Markham, Ontario": "value": 71}

Based on your updated question, I take it that you have this:
const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
and you want this:
result = [
{"Toronto, Ontario": 95},
{"Markham, Ontario": 71}
];
To do that, you need to split the number at the end of the string off, and then build objects with the two parts of the string. If you know there's only ever one :, then:
const result = start.map(str => {
const [city, number] = str.split(":");
return {
[city]: +number
};
});
Live Example:
const start = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
const result = start.map(str => {
const [city, number] = str.split(":");
return {
[city]: +number
};
});
console.log(result);
That uses destructuring to capture the two parts from split, then a computed property name to create a property with the city name, and + to coerce the number to number from string. (That's just one of your number-to-string options, see this answer for more options.)

reportData.fbcity = Object.keys(reportData.city).map((city) => {
return {
[city]: reportData.city[city]
};
})

You can use map and split
split with : and than build a object
+ is used to convert string to number
let data = ["Toronto, Ontario: 95", "Markham, Ontario: 71"];
let op = data.map(val=>{
let [key,value] = val.split(':')
return {[key]: +value}
})
console.log(op)

Related

Javascript filter array with regex

I am struggling at the moment with making a new array of strings from another array that I have to filter for certain pattern.
Example:
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"
I guess this could be matched from this string as well. But my initial approach was to split this string at each / :
let splitArr = originalString.split('/');
// splitArr = ["4162416245", "OG74656489", "OG465477378", "NW4124124124", "NW41246654"]
Basically what I do have to achieve is to have 2 different array that is filtered down by pattern of the start of this strings. OG and NW is always fix won't change but numbers after I don't know.. Backend sends this data as OG(original ticket) NW(new ticket) so those prefixes are fix, I have to check for string starting with them and put them in they array:
ogArr = ["OG74656489", "OG465477378"]
nwArr = ["NW4124124124", "NW41246654"]
If you want 2 separate arrays, you can use filter and startsWith
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');
const ogArr = splitArr.filter(s => s.startsWith("OG"));
const nwArr = splitArr.filter(s => s.startsWith("NW"));
console.log(ogArr);
console.log(nwArr);
Another option could be using reduce to travel the collection once, and pass in an object with 2 properties where you can extract the data from.
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654";
let splitArr = originalString.split('/');
const res = splitArr.reduce((acc, curr) => {
if (curr.startsWith("OG")) acc.og.push(curr)
if (curr.startsWith("NW")) acc.nw.push(curr)
return acc;
}, {
"nw": [],
"og": []
})
console.log(res);
You can also use the Array.prototype.reduce() method to add the elements into an object containing all tickets.
This would lead to this results :
{
"OG": [
"OG74656489",
"OG465477378"
],
"NW": [
"NW4124124124",
"NW41246654"
]
}
let originalString = "4162416245/OG74656489/OG465477378/NW4124124124/NW41246654"
const tickets = originalString.split('/').reduce((acc, curr) => {
if(curr.startsWith('OG')) acc["OG"].push(curr)
else if(curr.startsWith('NW')) acc["NW"].push(curr)
return acc
}, {OG: [], NW: []})
console.log(tickets)

Find Unique value from an array based on the array's string value (Javascript)

so I want to find unique values from an array.
so for example I have this array:
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
so I want to find the first matching value for each unique item.
for example, in the array, I have two strings with the shape prefix, six items with the size prefix, and two items with the height prefix.
so I want to output to be something like
const requiredVal = ["shape-10983", "size-2364", "height-3399"]
I want only the first value from any set of different values.
the simplest solution will be to iterate on the list and storing what you got in a dictionary
function removeSimilars(input) {
let values = {};
for (let value of input) {//iterate on the array
let key = value.splitOnLast('-')[0];//get the prefix
if (!(key in values))//if we haven't encounter the prefix yet
values[key] = value;//store that the first encounter with the prefix is with 'value'
}
return Object.values(values);//return all the values of the map 'values'
}
a shorter version will be this:
function removeSimilars(input) {
let values = {};
for (let value of input)
values[value.splitOnLast('-')[0]] ??= value;
return Object.values(values);
}
You could split the string and get the type and use it aks key for an object along with the original string as value. At result take only the values from the object.
const
data = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'],
result = Object.values(data.reduce((r, s) => {
const [type] = s.split('-', 1);
r[type] ??= s;
return r;
}, {}));
console.log(result);
If, as you mentioned in the comments, you have the list of prefixes already available, then all you have to do is iterate over those, to find each first element that starts with that prefix in your full list of possible values:
const prefixes = ['shape', 'size', 'height'];
const list = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884']
function reduceTheOptions(list = [], prefixes = [], uniques = []) {
prefixes.forEach(prefix =>
uniques.push(
list.find(e => e.startsWith(prefix))
)
);
return uniques;
}
console.log(reduceTheOptions(list, prefixes));
Try this:
function getRandomSet(arr, ...prefix)
{
// the final values are load into the array result variable
result = [];
const randomItem = (array) => array[Math.floor(Math.random() * array.length)];
prefix.forEach((pre) => {
result.push(randomItem(arr.filter((par) => String(par).startsWith(pre))));
});
return result;
}
const mainArr = ['shape-10983', 'size-2364', 'size-7800', 'size-4602', 'shape-11073', 'size-15027', 'size-15030', 'size-15033', 'height-3399', 'height-5884'];
console.log("Random values: ", getRandomSet(mainArr, "shape", "size", "height"));
I modified the #ofek 's answer a bit. cuz for some reason the ??= is not working in react project.
function removeSimilars(input) {
let values = {};
for (let value of input)
if (!values[value.split("-")[0]]) {
values[value.split("-")[0]] = value;
}
return Object.values(values);
}
create a new array and loop over the first array and check the existing of element before in each iteration if not push it to the new array

How to turn a string onto a map?

I need to turn a string formatted like that:
string = "John:31,Miranda:28"
Onto this;
obj = { "John" => 31, "Miranda" => 28 }
I did this :
const class = new Map();
array = string.split(",");
And obviously I do not know what do with it because after the split I get something like this:
["John:31", "Miranda:28"]
And I don't know how to turn it onto an object (using the ":" as a arrow)... Maybe I don't need to use the array as an intermediary? Any thoughts? Thanks
You can use split to split by comma, and then map on the resulting strings to split again by colon, and feed the resulting array of arrays into the Map constructor.
For instance, if you want the map keyed by the names, which I suspect you do:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => entry.split(":")));
console.log(map.get("John")); // "31" (a string)
If you want the numbers to be numbers, not strings, you'll need to convert them:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const parts = entry.split(":");
parts[1] = +parts[1];
return parts;
}));
console.log(map.get("John")); // 31 (a number)
My answer here goes into some detail on your options for converting from string to number.
If you want the map keyed by value instead (which I suspect you don't, but...), you just have to reverse the order of the inner array entries:
const string = "John:31,Miranda:28"
const map = new Map(string.split(",").map(entry => {
const [name, num] = entry.split(":");
return [num, name];
}));
console.log(map.get("31")); // John
So split on the commas, loop over it and split on the colon, and build the object.
var myString = "John:31,Miranda:28"
var myObj = myString.split(',').reduce(function (obj, part) {
var pieces = part.split(':')
obj[pieces[0]] = pieces[1]
return obj
}, {})
You could try something like this:
const data = "John:31,Miranda:28"
const splitData = data.split(',')
const result = splitData.reduce((newObject, item) => {
const [name, age] = item.split(':')
return {
...newObject,
[name]: parseInt(age)
}
}, {})
console.log(result)
I'll just add this here:
Basically, split string by the comma, then the colon.
Combine result into a map
const test = "John:31,Miranda:28";
console.log(test);
const obj = test.split(/,/).map(item => item.split(/:/));
console.log(obj);
const _map = new Map(obj);
console.log(_map);
console.log(_map.get("John"))

Convert JSON to Array of Objects using lodash

I have a JSON object in NoSql database in this format. We are getting this data after migrating some records from some other database and these are multi-valued fields.(Basically we are trying to clean the data for further processing).
{
"BPContName":"aName;bName;cName",
"BPContEmail":"aEmail;bEmail;cEmail",
"BPContPWID":"aPWID;bPWID;cPWID"
}
I want to add another key "bpTableDataName" in the same JSON which should have this format and values,
"bpTableDataName": [
{
"name": "aName",
"email": "aEmail",
"pwdid": "aPWID"
},
{
"name": "bName",
"email": "bEmail",
"pwdid": "bPWID"
},
{
"name": "cName",
"email": "cEmail",
"pwdid": "cPWID"
}
],
Is there a way we can achieve this using lodash?
Try following code -
o = {
"BPContName": "aName;bName;cName",
"BPContEmail": "aEmail;bEmail;cEmail",
"BPContPWID": "aPWID;bPWID;cPWID"
}
map = { "BPContName" : "name", "BPContEmail": "email", "BPContPWID": "pwdid" }
const result = _.reduce(o, (arr, v, k) => ( v.split(";").forEach((x,i) => _.set(arr, `${i}.${map[k]}`, x)), arr ), [])
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>
You can use split() to split the values into an array.
Then iterate over the array and create the require json and then push that into results.
Check this out.
var data = {
"BPContName":"aName;bName;cName",
"BPContEmail":"aEmail;bEmail;cEmail",
"BPContPWID":"aPWID;bPWID;cPWID"
}
var names = data.BPContName.split(';');
var emails = data.BPContEmail.split(';');
var pwids = data.BPContPWID.split(';');
var results = [];
for(var i = 0 ; i < names.length; i++) {
var obj = {
name: names[i],
email: emails[i],
pwdid: pwids[i]
}
results.push(obj);
}
console.log(results)
You could reduce the entries returned by Object.entries like this:
let obj = {
"BPContName": "aName;bName;cName",
"BPContEmail": "aEmail;bEmail;cEmail",
"BPContPWID": "aPWID;bPWID;cPWID"
}
let bpTableDataName = Object.entries(obj).reduce((r, [key, value]) => {
let splits = value.split(";");
key = key.replace("BPCont", "").toLowerCase();
splits.forEach((split, i) => (r[i] = r[i] || {})[key] = split)
return r;
}, [])
obj.bpTableDataName = bpTableDataName;
console.log(obj)
Object.entries returns an array of key-value pair. Loop through each of them
split the each value at ;
get the key by removing BPCont part and making it lowerCase
Loop through the splits and update specific keys of objects at each index
Update:
Since you have an extra d in the output's key, you can create a mapping object:
propertyMap = {
"BPContName": "name",
"BPContEmail": "email",
"BPContPWID": "pwdid"
}
And inside the reduce, change the replace code to this:
key = propertyMap[key]
Using Object.assign, Object.entries, Array#map and the spread operator make this trivial
const inputdata = {
"BPContName":"aName;bName;cName",
"BPContEmail":"aEmail;bEmail;cEmail",
"BPContPWID":"aPWID;bPWID;cPWID"
};
const t1=Object.assign({},...Object.entries(inputdata).map(([k,v])=>({[k]:v.split(';')})));
inputdata.bpTableDataName=t1.BPContName.map((name,i)=>({name,email:t1.BPContEmail[i],pwdid:t1.BPContPWID[i]}));
console.log(inputdata);
Of course, it wouldn't be me without a one-liner
const obj = {
"BPContName":"aName;bName;cName",
"BPContEmail":"aEmail;bEmail;cEmail",
"BPContPWID":"aPWID;bPWID;cPWID"
};
// one line to rule them all
obj.bpTableDataName=Object.entries(obj).reduce((r,[k,v])=>(v.split(';').forEach((v,i)=>(r[i]=r[i]||{})[{BPContName:'name',BPContEmail:'email',BPContPWID:'pwdid'}[k]]=v),r),[]);
//
console.log(obj);
Basically what you need is to zip it.
Snippet:
let obj = {"BPContName":"aName;bName;cName","BPContEmail":"aEmail;bEmail;cEmail","BPContPWID":"aPWID;bPWID;cPWID"},
res = _.zipWith(
..._.map(obj, v => v.split(';')),
(name, email, pwid) => ({name, email, pwid})
);
console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Note, the sequence of the parameters we have to put such a way, the original object give us values when using Object.values or giving us keys when using Object.keys usually it is alphabetical order. But, In case in any env the order is not guranted we can sort it with a sequence of keys as a metadata.
Or else you can explicitly pass the arguments like:
(obj.BPContName.split(';'), obj.BPContEmail.split(';'), obj.BPContPWID.split(';'))
You can use lodash's _.flow() to create a function. Use _.map() with _.overArgs() to create a function that splits the values, format the key, and then converts them to an array of pairs using _.unzip(), for example [['name', 'x'], ['name', 'y']]. Transpose the array of arrays with _.unzip() to combine pairs of different properties. Then use _.map() to iterate, and convert each array of pairs to an object using _.fromPairs().
const { flow, partialRight: pr, map, unzip, overArgs, times, size, constant, split, fromPairs } = _
const keysMap = new Map([['BPContName', 'name'], ['BPContEmail', 'email'], ['BPContPWID', 'pwdid']])
const formatKey = key => keysMap.get(key)
const splitVals = pr(split, ';')
const fn = flow(
pr(map, overArgs(
(vals, k) => unzip([vals, times(size(vals), constant(k))]),
[splitVals, formatKey])
),
unzip, // transpose
pr(map, fromPairs) // convert each pairs array to object
)
const data = {
"BPContName":"aName;bName;cName",
"BPContEmail":"aEmail;bEmail;cEmail",
"BPContPWID":"aPWID;bPWID;cPWID"
}
const results = fn(data)
console.log(results)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Converting a String to Multiple objects (javascript)

I have the following string: Jack:13,Phil:15,Lucy:12I'm trying to fetch objects from this string.
This string would have 3 people objects with their ages. How can this be achieved?
I've tried the following:
var s = 'Jack:13,Phil:15,Lucy:12'
var obj1 = eval("("+s+")");
var obj2 = JSON.parse(s);
Logging any of the obj variables returns errors. Am I missing a simple trick here? Any explanation would be appreciated, thanks.
In general, if you're doing replaces on a string to turn it into something you can pass eval or JSON.parse, that's probably not your best approach. An in particular, avoid using eval (or its cousin new Function) when you can (you certainly can here), and always avoid eval (or its cousin new Function) with untrusted input.
A pair of splits with map does it:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => e.split(":"))
.map(([name, age]) => ({name, age}));
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) { return e.split(":"); })
.map(function(e) { return {name: e[0], age: e[1]}; });
console.log(people);
I'm not sure why I did two maps rather than just doing the second split and creating the object in the same callback; I guess I'm thinking more and more in a "functional programming" way. I'd change it, but Eddie's answer already does it in a single map, so...
...(edit) but since it looks like you wanted separate properties rather than using the person's name like Eddie did, here's an example of the above but with just a single map:
const s = 'Jack:13,Phil:15,Lucy:12'
const people = s.split(",")
.map(e => {
const [name, age] = e.split(":");
return {name, age};
});
console.log(people);
...or in ES5:
var s = 'Jack:13,Phil:15,Lucy:12'
var people = s.split(",")
.map(function(e) {
var parts = e.split(":");
return {name: parts[0], age: parts[1]};
});
console.log(people);
You can split() the string and use map() to loop thru the array. This will return an array of objects.
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').map(o => {
let [k, v] = o.split(':');
return {[k]: v};
});
console.log(result);
If you want a single object, you can use reduce
var s = 'Jack:13,Phil:15,Lucy:12';
var result = s.split(',').reduce((c, o) => {
let [k, v] = o.split(':');
return Object.assign(c, {[k]: v});
}, {});
console.log(result);
You can try with:
const result = s.split(',')
.map(value => value.split(':'))
.reduce((acc, [name, value]) => {
acc[name] = +value;
return acc;
}, {});
Output:
{
"Jack": 13,
"Phil": 15,
"Lucy": 12
}
As I'm sure you've worked out there are many ways to do this, I thought I'd add another method
let s = 'Jack:13,Phil:15,Lucy:12'
let obj = {};
s.split(",").forEach(part => {
obj[part.split(":")[0]] = part.split(":")[1];
})
console.log(obj);
This is a simple split the string and then on each item of the new array do a split and push the results into an empty object already declared.
You could split the parts and build a new object with key/value pairs.
var string = 'Jack:13,Phil:15,Lucy:12',
result = Object.assign(...string
.split(',')
.map(s => (([k, v]) => ({ [k]: v }))(s.split(':')))
);
console.log(result);
For getting an array with objects
var string = 'Jack:13,Phil:15,Lucy:12',
result = string
.split(',')
.map(s => (([name, age]) => ({ name, age }))(s.split(':')));
console.log(result);
Easy to do with .map():
var s = 'Jack:13,Phil:15,Lucy:12';
var items = s.split(',')
.map((entry) => entry.split(':'))
.map((item) => ({name: item[0], age: item[1]}));
console.log(items);

Categories