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

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:

Related

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

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)

Convert array to array of objects [duplicate]

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);

Change array in to object in react js [duplicate]

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);

Create a key value pair for both the current key and value

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)

Categories

Resources