Change array in to object in react js [duplicate] - javascript

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

Related

JavaScript modify Array of Objects and alter contained data

I am having difficulties formatting some data. Currently, I receive data in the following structure.
[
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
I essentially need to modify this or even create a new object, that takes the following structure.
[
{
id: 1, //q1
answers: [
{
answer: '5',
},
],
},
{
id: 2, //q2
answers: [
{
answer: '13',
},
{
answer: '12',
},
],
},
{
id: 3, //q3
answers: [
{
answer: 'test',
},
],
},
];
So the id in the above would be obtained by remove the q and getting the number in the first data object. It would then have an answers array that would have an object for each answer.
I have been attempting this but have gotten lost. I don't know if I should use loops, mapping, filters etc. To be honest, the furthest I have got so far is obtaining the keys
var modified = data.map(function(item) {
return Object.keys(item)
})
I have created a JSFiddle where I have been attempting to do this.
Is there any way I can achieve the data I am after?
Many thanks
Please use map function.
const data = {
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
};
const result = Object.keys(data).map(key => {
let item = {id: key.substring(1), answers: []};
if(typeof data[key] === "string")
item.answers.push({answer: data[key]});
else
item.answers = data[key].map(val => ({answer: val}));
return item;
});
console.log(result)
const inputData = [
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
function answerMapper(objVal, id){
return Array.isArray(objVal)
?
{ id, answers: objVal.map(answer => ({ answer }))}
:
{ id, answers: [{answer: objVal }] }
}
function formatObject(obj){
return Object.keys(obj).map((k, i) => answerMapper(obj[k], i+1));
}
const result = inputData.map(obj => formatObject(obj));
// remove flatMap if your inputData has more than one entry
console.log(result.flatMap(x => x));
map over the first element of the data with Object.entries, grab the key and value, create a new answers array and return a new object.
const data = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const out = Object.entries(data[0]).map(obj => {
const [ key, value ] = obj;
const id = Number(key[1]);
// If the the value is an array
// return a new array of mapped data
// Otherwise return an array containing
// one object
const answers = Array.isArray(value)
? value.map(el => ({ answer: el }))
: [{ answer: value }];
// Return the new object
return { id, answers };
});
console.log(out);
lets create a pure function which accepts the object in the array like so
const processObject = obj => Object.keys(obj).map(id => {
const answer = obj[id];
const answers = Array.isArray(answer) ? answer : [answer]
const answerObjectArray = answers.map(ans => ({
answer: ans
}));
return {
id: +id.substring(1),
answers: answerObjectArray
}
});
const dataArray = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const output = processObject(dataArray[0]);
console.log(output);

JavsScript: Reduce array of dictionary into Array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I get this response from REST API.
"items": [
{
"name": "one"
},
{
"name": "two"
}
]
I want to reduce it to array ["one", "two"]. Can someone please tell me how?
const res = {
items: [{
name: 'one'
},
{
name: 'two'
}
]
};
console.log(res.items.map(res => res.name));
try this
using map
var items = [
{
name: "one",
},
{
name: "two",
},
];
console.log(items.map((item) => item.name));

How can i find an array of objects out of an array [duplicate]

This question already has answers here:
How to traverse through array within an object and return each array element as the second key value pair, along with its' corresponding ID
(2 answers)
Closed 1 year ago.
i have an array
let data = [
{
A_ID: 'ABC',
C_Array: ["123","456","789"]
},
{
A_ID: 'DEF',
C_Array: ["444","555","666"]
}
]
and i want to create a new array like so that for each C_Array i get its coresponding A_ID,
like
let newData = [
{
A_ID: 'ABC',
C_ArrayValue: "123"
},
{
A_ID: 'ABC',
C_ArrayValue: "456"
},
]
How can i do that in JS
let data = [
{
A_ID: 'ABC',
C_Array: ["123", "456", "789"]
},
{
A_ID: 'DEF',
C_Array: ["444", "555", "666"]
}
]
const newArray = data.map((outerNode) => {
return outerNode.C_Array.map((innerNode) => {
return {
A_ID: outerNode.A_ID,
C_ArrayValue: innerNode
}
})
});
console.log(newArray);

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

How to create a JSON array from below JSON with key-value? [duplicate]

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
How to convert an object to array of objects [duplicate]
(5 answers)
Closed 3 years ago.
Need to create below output from the JSON obj
let obj = {"id" : 1, "name": "John"};
expected result:
[
{key: "id", value: "1"},
{key: "name", value: "John"}
]
You can get the keys of obj using Object.keys() and map them to objects.
const obj = {
"id": 1,
"name": "John"
};
const result = Object.keys(obj).map(k => ({
key: k,
value: obj[k]
}));
console.log(result);
You can try this:
JSON.stringify(
Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({
key: key,
value: value
}))
)

Categories

Resources