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]
})
}
Related
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);
So I have an existing array with three objects:
[ { date: 3/12/2022, oService: 10}
{ date: 3/13/2022, oService: 12, aService: 1}
{ date: 3/13/2022, oService: 1 }]
Based on the date, I would like to get something that looks like the following:
[ {date: 3/12/2022, oService: 10}
{date: 3/13/2022, oService: 13, aService: 1}]
additionally, I could have up to 10 services, so I cant reduce by prev.oService. I'll have an array of services that looks something like:
const Services = [aService, bService, cService, oService, yService]
I think it's best to think of the problem as 2 different steps:
First, get all things that belong to the same date together. This is a groupBy that you should be able to look up on StackOverflow or borrow from an existing library.
Then, you merge each of the date groups in to a single object.
The merge operation is a bit more custom than the groupBy operation. You can implement it in many ways. I would propose to:
Implement merge to deal with just 2 objects
Inside merge, loop over all unique keys in those objects and sum them (excluding the date key)
To apply merge to a date group, use reduce. Note that it's safe to not provide a seed argument here, because you are guaranteed to not have empty groups.
// Merge two date-service entries in to one
const merge = (a, b) => {
const merged = Object.assign({}, a);
Object.keys(b).forEach(k => {
if (k !== "date")
merged[k] = (merged[k] || 0) + b[k];
});
return merged;
};
const input = [ { date: "3/12/2022", oService: 10},
{ date: "3/13/2022", oService: 12, aService: 1},
{ date: "3/13/2022", oService: 1 }];
// Create groups that have a matching date
const byDate = groupByProp("date", input);
// Reduce each group to a single item by merging
const all = Object.values(byDate).map(xs => xs.reduce(merge));
console.log(all);
// A basic `groupBy` implementation
function groupByProp(prop, xs) {
return xs.reduce(
(groups, x) => {
const k = x[prop];
if (!groups[k]) groups[k] = [x];
else groups[k].push(x);
return groups;
},
{}
);
}
I have the following array of objects.
var array = [
{
name: 'abc',
place1: 'def'
},
{
name: 'abc',
place2: 'ghi'
}]
I am trying to get the following output
var array = [[name:'abc'],[place1:'def'],[place2:'ghi']]
this is my attempt:
let arr = []
array.forEach((element,index) => {
const keys = Object.keys(element)
keys.forEach(e => {
let temp = [];
temp[0] = e;
temp[1] = element[e];
if(!arr.indexOf(temp)
arr.push(temp)
});
});
but I am not getting the expected output.
I'm not sure how a an array of objects with different properties would help you. You should probably use one object with all properties or an array of entries.
However, to get the result you want - merge the array of objects to a single object by spreading into Object.assign() to remove duplicates. Then convert to an array of entries [key, value], and map back to an array of objects:
const array = [{"name":"abc","place1":"def"},{"name":"abc","place2":"ghi"}]
const result = Object.entries(Object.assign({}, ...array))
.map(([k, v]) => ({ [k]: v })) // remove the map to get an array of entries
console.log(result)
let states = ["Georgia","California","FL","TX","MA","NJ"];
How do I convert the states array into Id and Name array collection using lodash.
Is there a way to convert the array in below format ( image shown below):
You don't really need lodash to do that.
let states = ["Georgia","California","FL","TX","MA","NJ"];
let result = states.map((item) => {
return {
id: item,
name: item}})
console.log(result)
You do pretty much the same with lodash
import _ from 'lodash';
result = _.map(states, (item) => {
return {
id: item,
name: item}})
let states = ["Georgia","California","FL","TX","MA","NJ"];
const newObj = [];
_.each(states, state => newObj.push({ id: state, name: state }));
console.log(newObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_.each performs a function on each item of an Array. With that you can create a new object for each state and push that into a new Array. Note: this could also be accomplished with JavaScript's built in .map.
----- UPDATE -----
Why did I make this complicated many years ago?
const states = ["Georgia","California","FL","TX","MA","NJ"];
const newObj = states.map(state => ({ id: state, name: state }));
console.log(newObj);
No need to use lodash, just map through the array and return a new object for each item in the array.
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} />))}
</>
)