This question already has answers here:
Most efficient method to groupby on an array of objects
(58 answers)
Closed 2 years ago.
I have this array of object i want to convert:
let ordNumbers = [
{"seq":1,"ordNumber":"221"},
{"seq":1,"ordNumber":"224"},
{"seq":2,"ordNumber":"221"}
]
to this format
let filteredOrders = [
{"seq":[1,2],"ordNumber":"221"},
{"seq":1,"ordNumber":"224"}
]
Based on the order numbers i want the above format
You mean something like this?
var ordNumbers = [
{
"seq": 1,
"ordNumber": "221"
},
{
"seq": 1,
"ordNumber": "224"
},
{
"seq": 2,
"ordNumber": "221"
}
]
// formatted as { ordNumber: [seq] }
var pairs = ordNumbers.reduce((acc, v) => {
acc[v.ordNumber] = (acc[v.ordNumber] || []).concat(v.seq);
return acc;
}, {});
// formatted as [{"seq": [seqs], "ordNumber": ordNumber}]
var res = Object.keys(pairs).map(v => ({
seq: pairs[v],
ordNumber: v
}));
console.log(res);
let ordNumbers = [
{"seq":1,"ordNumber":"221"},
{"seq":1,"ordNumber":"224"},
{"seq":2,"ordNumber":"221"}
]
let ordMap = {}
for (let el of ordNumbers) {
// if the ordNumber exists in the map then pushing el.seq to it's value else setting el.seq as
// the value
ordMap[el.ordNumber] = ordMap[el.ordNumber] ? [...ordMap[el.ordNumber], el.seq] : [el.seq]
}
const result = Object.keys(ordMap).map(val => ({seq: ordMap[val], ordNumber: val}));
console.log(result)
Related
This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 1 year ago.
I've got an object with different values .
let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]
How can I foreach them and then put them in an object and pick a name for them like this :
"photo_type": {
"Personal": "1000",
"sport": "2100",
"Industrial": "1200",
"Commercial": "2300",
"Fashion": "1300",
"Documentary": "2600"
}
I dont want them to be like 0 and 1 and 2.
You could create an object with Object.assign and by spreading the array.
let array = [{ Personal: "1000" }, { sport: "2100" }, { Industrial: "1200" }, { Commercial: "2300" }, { Fashion: "1300" }, { Documentary: "2600" }],
object = Object.assign({}, ...array);
console.log(object);
You can try this
const arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},{"Fashion": "1300"},{"Documentary": "2600"}]
let result = {}
arr.forEach(member => {result = {...result, ...member}}
This question already has answers here:
Easy way to turn JavaScript array into comma-separated list?
(22 answers)
Closed 2 years ago.
I have a json like this:
[ {"numbers":["1","2","3","4"],
"city":"Tokio",
"color":"blue",
},
{"numbers":["5","6","7","8"],
"city":"Tokio",
"color":"green",
},
.........
]
and i need to convert to another json with javascript like this:
[ {"numbers":"1,2,3,4",
"city":"Tokio",
"color":"blue",
},
{"numbers":"5,6,7,8",
"city":"Tokio",
"color":"blue",
},
.........
]
so, i need to convert the array of numbers in a string, any idea?
Thanks in advance.
For an array use this:
const jsonObjArray = [
{
"numbers":["1","2","3","4"],
"city":"Tokio",
"color":"blue"
},
{
"numbers":["1","2","3","4"],
"city":"New York",
"color":"red"
},
{
"numbers":["1","2","3","4"],
"city":"Rome",
"color":"green"
}
]
const result = [];
jsonObjArray.map( item => {
const numbers = item["numbers"];
let numbersAsString = numbers.join(",");
result.push({...item, numbers: numbersAsString});
});
console.log(result)
Answer 1:
const data ={"numbers":["1","2","3","4"],
"city":"Tokio",
"color":"blue",
};
let modifyResult={}
for (const key in data) {
if (data.hasOwnProperty(key)) {
if(key==="numbers"){
modifyResult[key]= data["numbers"].join(", ");
}else{
modifyResult[key]= data[key];
}
}
}
console.log("Final:",modifyResult);
Hope, this will solve your problem.
OutPut Screen-Shot:
Answer 2:
As per your comment you want to transform the array of object with their key, So I am providing Second answer
const data = [ {"numbers":["1","2","3","4"], "city":"Tokio", "color":"blue", }, {"numbers":["5","6","7","8"], "city":"Tokio", "color":"green", }];
const finalresult = data.map(item => {
letcontainer = {};
container = {...item};
container.numbers = item.numbers.join(", ");
return container;
})
console.log(finalresult);
OutPut Screen-shot:
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
Closed 3 years ago.
This is my array format
let array = [
0: {
key:"name",
value: "John"
},
1: {
key:"age",
value:25
},
2: {
key:"job",
value:"software engineer"
},...
];
Change this array to object in given below format
{
name: "John",
age: 27,
job: "software engineer"
}
You can achieve it using forEach on the array.
Give this a try:
const array = [{
key: "name",
value: "John"
}, {
key: "age",
value: 25
}, {
key: "job",
value: "software engineer"
}];
const expected = {};
array.forEach(item => expected[item.key] = item.value);
console.log(expected);
You can use Array.prototype.reduce() to do this:
let array = [
{
key:"name",
value: "John"
},
{
key:"age",
value:25
},
{
key:"job",
value:"software engineer"
}
];
let result = array.reduce((a,b) => {
a[b.key] = b.value;
return a;
}, {});
console.log(result);
All you need to do is to loop over the array using forEach, for loop, while loop etcand push the values in a new object.
Also make sure that your array syntax is correct because the way you have mentioned it in the question is incorrect.
const data = [{ key:"name", value: "John" },{ key:"age", value:25 },{ key:"job", value:"software engineer" } ];
const res = {};
data.forEach(item => { res[item.key] = item.value});
console.log(res);
I have an array:
let ar = [
{
uid:1,
flat_no: 1
},
{
uid:2,
flat_no: 2
},
{
uid:1,
flat_no:3
}
];
If uid are same then I want to remove duplicate uid and concatenate its flat_no. The output array should be like this:
[
{
uid:1,
flat_no: [1,3]
},
{
uid:2,
flat_no: 2
}
];
You can use a combination of Array.reduce and Array.find.
If you find an existing item in your accumulator array, just update it's flat_no property, otherwise push it to the accumulator array.
let arr = [
{
uid: 1,
flat_no: 1
},
{
uid: 2,
flat_no: 2
},
{
uid: 1,
flat_no: 3
}
]
arr = arr.reduce((arr, item) => {
const existing = arr.find(innerItem => innerItem.uid === item.uid)
if (existing) {
existing.flat_no = Array.isArray(existing.flat_no)
? existing.flat_no
: [existing.flat_no]
existing.flat_no.push(item.flat_no)
} else {
arr.push(item)
}
return arr
}, [])
console.log(arr)
You can iterate over your array and fill an object (used as a hashmap here).
Once done, you extract the values to get your result.
let hashResult = {}
ar.forEach(element => {
if (hashResult[element.uid] == undefined) {
hashResult[element.uid] = { uid: element.uid, flat_no: [] }
}
hashResult[element.uid].flat_no.push(element.flat_no)
})
let result = Object.values(hashResult)
console.log(new Date(), result)
You can do this in a concise way with a single Array.reduce and Object.values to match your desired output:
let data = [ { uid:1, flat_no: 1 }, { uid:2, flat_no: 2 }, { uid:1, flat_no:3 } ];
const result = data.reduce((r, {uid, flat_no}) => {
r[uid] ? r[uid].flat_no = [r[uid].flat_no, flat_no] : r[uid] = {uid, flat_no}
return r
}, {})
console.log(Object.values(result))
1)Reduce the initial array to an object which has uid as the key and the flat_no as the value.
2)Then run a map on the keys to convert it into an array of objects with uid and flat_no.
1) First Step Code
let ar = [{uid:1, flat_no: 1},{uid:2, flat_no: 2},{uid:1, flat_no:3}];
let outputObj = ar.reduce((outputObj,currObj,currIndex) => {
let {uid,flat_no} = currObj
if (outputObj[uid]) {
outputObj[uid].push(flat_no)
}
else {
outputObj[uid] = [flat_no]
}
return outputObj
},{})
2)
let finalOutput = Object.keys(outputObj).map(key =>
({uid:key,flat_no:outputObj[key]}))
console.log(finalOutput)
I currently have an array of simple objects:
data = [{ "alternative hip hop": 3 }, { "escape room": 4 }, ...]
...to which I'd like to transform into
newData = [
{ "name": "alternative hip hop", "count": 3 },
{ "name": "escape room", "count" 4 }
]
Is this doable with a map? I've failed at figuring out how to do so with one.
lodash responses are welcome as well
Assuming each item in the data has a single key/value pair, you'd want:
data.map(obj => {
const key = Object.keys(obj)[0]; //Just get the first key we find
return {
name: key,
count: obj[key]
};
})
I hope I didn't write it false on my Mobile, but here is a way:
let newData = data.map(e => {
for(let key in e) {
return {
name: key,
count: e[key]
};
}
});
Im not familiar with loadsh, but with javascript you can do the following:
var data = [{ "alternative hip hop": 3 }, { "escape room": 4 }]
var newData = [];
data.forEach((item)=>{ //loop over the array
Object.keys(item) //get the object keys
.map((keyName)=>{ //loop over each key
newData.push({name:keyName, count:item[keyName]}) //insert it into the new array
})
})
console.log(newData)