Convert array to array of objects [duplicate] - javascript

This question already has answers here:
Javascript string array to object [duplicate]
(4 answers)
Convert array of string to array of object using es6 or lodash
(4 answers)
Convert array of strings into an array of objects
(6 answers)
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 3 years ago.
I have an array like this:
const categories = ["Action", "Comedy", "Thriller", "Drama"]
And I would like to convert it to this format:
const displayedCategories = [{"type": "Action", "isDisplayed": true},{"type": "Comedy", "isDisplayed": true},{"type": "Thriller", "isDisplayed": true},{"type": "Drama", "isDisplayed": true}]
Any advice ? :)

You can do so by using map:
const categories = ["Action", "Comedy", "Thriller", "Drama"];
const newCategories = categories.map(category => ({
type: category,
isDisplayed: true
}));
console.log(newCategories);

You can do so with the map method:
const displayedCategories = categories.map(function(category) {
return { type: category, isDisplayed: true };
});

Maybe like This:
const categories = ["Action", "Comedy", "Thriller", "Drama"];
var out = [];
for(var key in categories){
out.push({"type": categories[key], "isDisplayed": true});
}
console.log(out);

use array.prototype.map to convert the array into an object
categories = catergories.map(val => {
var obj = {
type:val
//more properties go here
}
return obj
}

const categories = ["Action", "Comedy", "Thriller", "Drama"]
const displayedCategories = categories.map(category => { return {"type": category, "isDisplayed": true} })
console.log('displayedCategories :', displayedCategories);

Related

Merge array of objects into a single object [duplicate]

This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 1 year ago.
I have an array of objects in this shape;
const objectsArray = [{ projects: [] }, { components: [] }];
I want to merge it into a single object like this;
const mergedObject={ projects: [], components: [] }
Is there a better way of doing it other than this:
Object.keys(objectArray).map(key=>objectArray[key]).reduce((old,item)=>(
{...old,...item}
),{})
This might be a bit simpler:
const objectsArray = [{ projects: [1,2,3] }, { components: [4,5,6] }];
let mergedObjects
objectsArray.forEach(obj => mergedObjects = { ...mergedObjects, ...obj})
console.log(mergedObjects)

foreach array with one key [duplicate]

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}}

Convert json object from array of objects to string in JAVASCRIPT [duplicate]

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:

JavaScript: convert an array of string to an array of objects [duplicate]

This question already has answers here:
Convert array of strings into an array of objects
(6 answers)
Closed 2 years ago.
I have an array of strings: const names = ['name1', 'name2', name3']
And I need the following array of objects:
const newArray = [{ name: 'name1' }, { name: 'name2' }, { name: 'name3' }]
How can I create newArray from names, or even possibly convert names itself without creating brand new array?
This can be easily achieved with the map function.
const newArray = names.map((name) => {
return {
name
};
});
map() can do that for you:
const names = ['name1', 'name2', 'name3'];
const newArray = names.map(x=>{return{name:x};});
console.log(newArray);

Javascript Array of Objects one format to other [duplicate]

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)

Categories

Resources