How to change an array to a JSON format with javascript - javascript

I have an array which is in the below format
node=['ADSss|623', 'sss|635']
I want this to be in a json format as below
[
{
"623": "ADSss"
},
{"635": "sss"
}
]
Is there a simple way to achieve this? it is possible with map function, but i felt it is adding up too many lines of code

Assuming that you array only contain string of format ${value}|${key}, you can map those to an object:
const result = node.map((arrayEl) => {
// Split you array string into value and keys
const [value, key] = arrayEl.split('|');
// return an object key: value
return {[key]: value}
});
console.log(result);

In one line :
const node=['ADSss|623', 'sss|635'];
const json = node.reduce((p, n) => ({ ...p, [n.split('|')[1]]: n.split('|')[0] }), {});
const jsonArray = node.map(n => ({ [n.split('|')[1]]: n.split('|')[0] }));
console.log(json);
console.log(jsonArray);

Related

Javascript transform Object key to object values

I have an object that gives counts per day, and the date is the key. I would like to create a new object that has two properties (day and count) that uses the key:value pair.
This is the input format I have, and the structure I'm trying to achieve:
const have = {
"2022/01/01":0,
"2022/01/02":10,
"2022/01/03":12,
"2022/01/04":6,
"2022/01/05":8
};
const want = [
{day:"2022/01/01",count:0},
{day:"2022/01/02",count:10},
{day:"2022/01/03",count:12},
{day:"2022/01/04",count:6},
{day:"2022/01/05",count:8},
];
I've only gotten as far as printing each key and value to the log, but unsure how I can add these to a new object
let want = new Object();
Object.keys(have).forEach(function (key) {
console.log(key);
console.log(have[key]);
});
Here you go
const have = {
"2022/01/01": 0,
"2022/01/02": 10,
"2022/01/03": 12,
"2022/01/04": 6,
"2022/01/05": 8
};
const want = Object.keys(have).map((key) => ({
day: key,
count: have[key]
}));
You can try with array.map by taking up the object entries like,
const have = {
"2022/01/01":0,
"2022/01/02":10,
"2022/01/03":12,
"2022/01/04":6,
"2022/01/05":8
};
const want = Object.entries(have).map(([day, count]) => ({
day: day,
count: count
}));
console.log(want)
Iterate over keys and map them to a new array:
Object.keys(have).map(entry => { return { date: entry, count: have[entry]}})
You can use Object.entries for this:
const want = Object.entries(have).map(([day, count]) => ({day, count}))
Just use Array.map function to get your required format returned:
const want = Object.keys(have).map((key) => ({
day: key, count:have[key]
}));
Using a regular for..in loop, just traverse the keys, get the values and push to an empty array
let want = [];
for (let key in have) {
want.push({
day: key,
count: obj[key]
})
}

Re-ordering of JSON data

I am new to JSON and want to re-structure my JSON response,
JSON-structure now-
{
"map": {
"Cityname": "[Jammu, Srinagar]",
"Pincode": "[180001, 190001]"
}
}
How I need it to be-
[
{ Cityname: "Jammu", Pincode: 180001},
{ Cityname: "Srinagar", Pincode: 190001}
]
Is there a way to do so, I searched for some possible solutions but was unable to do so.
Here is a Dynamic way of doing so, should work with any json string with the same layout. I fixed some of your json string.
// first we use JSON.parse() to turn a json string into a JS Object.
const data = JSON.parse(`{ "map": { "cityName": ["Jammu", "Srinagar"], "pinCode": [180001, 190001]}}`);
// cities will hold our city objects
const cities = [];
// Object.entries(theObject) returns theObjects keys and values as an array
// EG:
// [[key, value], [key, value]]
// forEach() loops through each key, value pair.
// Because we know that we are going to get a key value pair,
// I destructured the array into it's key and values using:
// [key, values] = [properties];
Object.entries(data.map).forEach((prop) => {
const [key, values] = prop;
values.forEach((value, index) => {
// now we check that the current index is an object.
// we do this because we can't add a property and value otherwise.
if(typeof cities[index] != "object"){
cities[index] = {};
}
// now we set the current value
cities[index][key] = value;
})
})
console.log(cities);
Your JSON response, its not quite logical because there is not mapping between city and pincode. I assumed that cityname and pincode are in the same order in the arrays. I used exact json structure you provided in the question.
You can skip additional steps substring and parse if your json data have correct data types (Cityname string array / Pincode int array).
const json = {
"map": {
"Cityname": "[Jammu, Srinagar]",
"Pincode": "[180001, 190001]"
}
}
const someFunc = () => {
let output = [];
const {Cityname, Pincode} = json.map;
const citynameArray = (Cityname.substring(1, Cityname.length-1)).split(",");
const pincodeArray = JSON.parse(Pincode);
citynameArray.map((v,i) => {
output.push({Cityname: v, Pincode: pincodeArray[i]})
});
return output;
}
console.log(someFunc());

How to search in JSON with Javascript fast?

I have a lemmatization nested dictionaries, like
{
{"abbreviate": ["abbreviated","abbreviates","abbreviating"]},
{"abdicate": ["abdicated","abdicates","abdicating"]}
}
I want to fast search inside values to get the according key (find abbreviated → output abbreviate). Fast - because the file is about 6MB. This search will be used in a Chrome extension, so i would strongly prefer Javascript, not Python.
What are technics to accomplish such search?
It seems to me that you need to convert an object to a form for quick hash search:
{
abbreviated: 'abbreviate',
abbreviates: 'abbreviate',
abbreviating: 'abbreviate',
abdicated: 'abdicate',
abdicates: 'abdicate',
abdicating: 'abdicate',
};
const data = {
abbreviate: ['abbreviated', 'abbreviates', 'abbreviating'],
abdicate: ['abdicated', 'abdicates', 'abdicating'],
};
const dictionary = Object.keys(data).reduce((dict, key) => {
const records = data[key];
const obj = records.reduce((acc, val) => ({ ...acc, [val]: key }), {});
return { ...dict, ...obj };
}, {});
console.log(dictionary['abbreviated']);

Grouping with Lodash

I'm trying to group by "date" an object like this:
let myObj = [
{"date":"01/12","Deposits":50000},
{"date":"01/12","Withdrawals":10000}
]
So if I did groupBy "date", I'd want to receive:
[
{"date":"01/12", "Deposits":50000, "Withdrawals":10000}
]
I tried many different ways without success =(
Here is an approach without lodash, by using .reduce() and the spread syntax ... to extract your wanted properties. By using .reduce() you can group your array's objects into a larger aggregation object (ie: the acc), which you can then get the values() of to get your array of results:
const myObj = [{"date":"01/12","Deposits":50000},{"date":"01/12","Withdrawals":10000}];
const res = Object.values(myObj.reduce((acc, {date, ...rest}) => {
acc[date] = {...(acc[date] || {date}), ...rest};
return acc;
}, {}));
console.log(res);
If you wish to use lodash, here is an approach using _.groupBy(), _.map(), _.assign() and _.flow() which will allow you to make your own function to merge arrays by a key:
const myObj = [{"date":"01/12","Deposits":50000}, {"date":"01/12","Withdrawals":10000}];
const mergeArr = _.flow(
arr => _.groupBy(arr, 'date'),
group => _.map(group, arr => _.assign({}, ...arr))
);
const res = mergeArr(myObj);
console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
let result = _.map(_.groupBy(myObj, 'date'), value => _.assign(...value));

Convert object to array in Javascript / React

Using REST, I am retrieving an object(JSON format) which is to be converted to an array so that it can be inserted into a table.
This is done in the rendering function of React.
The input is updated every N minutes from the back-end.
How do I convert an object to an array?
I need only the values, not the keys, since the keys are already present as column values beforehand in the table itself.
You can use Object#values (ECMAScript 2017), but it's not supported by IE (see browser's compatibility).
Note: The ECMAScript 6 specification defines in which order the properties of an object should be traversed. This blog post explains the details.
const map = { a: 1, b: 2, c: 3 };
const result = Object.values(map);
console.log(result);
If you need to support IE, you can use Object#keys with Array#map:
const map = { a: 1, b: 2, c: 3 };
const result = Object.keys(map).map((key) => map[key]);
console.log(result);
I am not sure by map you mean the Map object or an ordinary JS object. However, just for variety I would like to mention that the Map objects are mostly (probably always) stringified like JSON.stringify([...myMap]). So if you happen to receive a Map object in JSON data may be you should do something like;
var myMap = new Map().set(1,"hey").set(2,"you"),
mapData = JSON.stringify([...myMap]),
values = JSON.parse(mapData).map(d => d[1]);
console.log("mapData:",mapData);
console.log("values:",values);
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And
return(
{conversations.map((conv) => (
))}
)
You can set initial value as array firstly. See this example:
const [conversations, setConversations] = useState([]); // fianal data is array
useEffect(() => {
const fetchConversations = async () => {
const res = await axios.get("/conversations/" + user._id);
setConversations(res.data);
};
fetchConversations();
}, [user._id]);
res.data convert to array by using useState([]) as initial value and convert to object by using useState({}).
And map this array:
return (
<>
{conversations.map((conv) =>
(<Conversations key={conv._id} conversation={conv} />))}
</>
)

Categories

Resources