This question already has answers here:
Convert Array to Object
(46 answers)
Closed 5 years ago.
I know this has been asked before, but every solution I found isn't doing it the way I need it.
The Array
[ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ]
Object I Need
{
"Title": "Default Text",
"Title2": "Default Text2"
}
Everything I try seems to return this which is wrong:
{ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} }
I've tried most things I found here on SO.. the last one I've tried that is formatting it wrong is:
let obj = Object.assign({}, arrayHere);
What I want:
What I keep getting, but is wrong:
Use Array.prototype.reduce() function:
var arr = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ],
result = arr.reduce((r,o) => {r[o.key] = o.value; return r; }, {});
console.log(result);
You could assign the single created objects with Array#map and Object.assign
var array = [{ key: "Title", value: "Default Text" }, { key: "Title2", value: "Default Text2" }];
object = Object.assign({}, ...array.map(o => ({ [o.key]: o.value })));
console.log(object);
const a = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
function convertArr(arr) {
const res = {};
a.forEach((item) =>
res[item.key] = item.value;
})
return res;
}
convertArr(a);
Using Array.prototype.map(),
var Object = [ {key: "Title", value: "Default Text"}, {key: "Title2", value: "Default Text2"} ];
var result = Object.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj; });
Related
If the fields key in a object is array, change the first value of arrays as a key value pair object in javascript.
var obj =
[
{ id:1, fields:["item", "2", "list"]},
{ id:2, fields:["sample", "1", "check"]}
]
function newObj(obj) {
let objFields = {};
modifiedObj.fields.forEach(field => objFields[field] = field);
modifiedObj.fields= objFields;
return modifiedObj;
}
var result = this.newObject(obj)
Expected Output
{
item: "item",
sample: "sample"
}
Try this:
var obj =
[
{ id:1, fields:["item", "2", "list"]},
{ id:2, fields:["sample", "1", "check"]}
]
function newObject(obj) {
let objFields = {};
obj.forEach(e => {
if(e.fields && e.fields.length>0)
objFields[e.fields[0]] = e.fields[0];
});
return objFields;
}
var result = this.newObject(obj);
console.log(result);
Here is a functional approach that makes use of Object.assign(), spread operator, and Array.map() to create the object you need.
const input = [
{ id: 1, fields: ["item", "2", "list"] },
{ id: 2, fields: ["sample", "1", "check"] }
];
const process = (input) => (Object.assign(...input.map(({ fields }) => (
fields.length ? { [fields[0]]: fields[0] } : {}
))));
console.log(process(input));
Your snippet was close, you just needed to clean up the variable names, and then using map makes it a bit neater too:
const obj = [
{id: 1, fields: ["item", "2", "list"]},
{id: 2, fields: ["sample", "1", "check"]}
]
function newObj(inputArray) {
let outputObject = {};
inputArray.map(item => item.fields[0])
.forEach(field => outputObject[field] = field);
return outputObject;
}
var result = newObj(obj)
console.log(result)
I would like to know how to change particular field by passing parameter type in javascript
I have object obj1, obj2, if the parameter type is string/array change the value field
as shown in expected output and vice-versa
function ChangeObj(obj, str){
var result = obj.map(e=> str==="string" ? ({...e, value:[e.value]}) : ({...e,value: e.value.toString()}) )
return result;
}
var obj1 =[
{ key: "country", id:0, value: "SG"},
{ key: "city", id:1, value: "IN"}
]
var obj2 = [
{ key: "cn", id:0, value: ["TH","MY"],img:"sample.jpg"},
{ key: "list", id:1, value: ["AU"], img:"item.jpg" }
]
var output1 = this.ChangeObj(obj1, "array");
var output2 = this.ChangeObj(obj2, "string");
Expected Output:
//output 1
[
{ key: "country", id:0, value: ["SG"] },
{ key: "city", id:1, value: ["IN"] }
]
// output 2
[
{ key: "cn", id:0, value: "TH", img:"sample.jpg"},
{ key: "cn", id:0, value: "MY", img:"sample.jpg" },
{ key: "list", id:1, value: "AU", img:"item.jpg" }
]
Because you want to generate multiple values when converting an array to a string, you can't use map directly. Instead, you could use reduce and then map the object value property inside the reduce:
function ChangeObj(obj, str) {
var result = obj.reduce((c, o) => c.concat(str === "array" ? [{ ...o,
value: [o.value]
}] : o.value.map(v => ({ ...o,
value: v
}))), []);
return result;
}
var obj1 =[
{ key: "country", id:0, value: "SG"},
{ key: "city", id:1, value: "IN"}
]
var obj2 = [
{ key: "cn", id:0, value: ["TH","MY"],img:"sample.jpg"},
{ key: "list", id:1, value: ["AU"], img:"item.jpg" }
]
var output1 = this.ChangeObj(obj1, "array");
var output2 = this.ChangeObj(obj2, "string");
console.log(output1);
console.log(output2);
Note that the sense of your ternary conditional is wrong and I have corrected it to str === "array" in this code.
Two issues:
You reversed the cases of string/array: in first case you want to wrap strings in arrays, but you pass "array" as second argument, while the function performs this wrapping when that argument is "string". So either you pass the wrong argument, or else the ternary expression should have the opposite condition.
When converting array to string you are currently applying toString to the array. But that will not multiply the number of objects in the output. It will just produce a comma separated string in one single object.
You can still use map to solve that last issue, but then apply a .flat to resolve the nested array that you'll get:
obj.map(e => str !== "string"
? {...e, value: [e.value]}
: e.value.map(value => ({...e,value}) )
).flat();
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'd like to convert this object that I receive from server to a JSON file so that I can use it in d3.js chart:
data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
The output should be:
{
"name" : "animal",
"children" : [
{"name":"dog", "value": 5},
{"name":"cat", "value": 4},
{"name":"fish", "value": 10}
]
}
What I came up with is:
var jsonText = [] ;
for ( key in data) {
jsonText.push({name : key.trim(), value : parseInt(data[key])});
}
But when I try to print out the object, I receive:
[object Object],[object Object],[object Object]
In addition to that I have no clue how to add other attributes to the JSON file. So appreciate your hints.
You can use Object.keys(data) and loop through the key to get the desired object structure.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
var res = {
name: "animal",
children: []
};
Object.keys(data).forEach((key)=>{
res.children.push(
{name:key.trim(), value: parseInt(data[key])}
);
});
console.log(res);
You're almost there (the array is formatted correctly), but you need the resulting array to be the value of the children property of the object. It would also be a bit easier to use Object.entries and map, which tranforms an array into another array based on the same elements:
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
};
const children = Object.entries(data)
.map(([name, value]) => ({ name: name.trim(), value: Number(value) }));
const output = { name: 'animal', children };
console.log(output);
Assuming you're manually adding a key like animal this should work and the values should be ints.
var data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
var children = Object.keys(data).map((key) => {
return {
name: key.trim(),
value: parseInt(data[key])
}
})
let result = JSON.stringify({
name: 'animal',
children
})
console.log(result);
That will return
{"name":"animal","children":[{"name":"dog ","value":5},{"name":"cat ","value":4},{"name":"fish ","value":12}]}
Try - console.log(JSON.stringify(jsonText))
Create an object with children key and push value to it
let data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let newObj = {
"name": "animal",
"children": []
}
for (let keys in data) {
newObj.children.push({
name: keys.trim(),
value: parseInt(data[keys], 10)
});
}
console.log(newObj)
You could do something like this
const data = {
"dog ":"5",
"cat ":"4",
"fish ":"12",
}
Object.keys(data).reduce((obj, animal) => ({
...obj,
children: [
...obj.children,
{
name: animal,
value: data[animal]
}
]
}), {name: "animal", children: []})
console.log(JSON.stringify(obj))
This is a cleaner way to get the desired results in my opinion
You can just iterate over the data object using for..in and push prop: value pair objects into you children array:
const data = {
"dog ": "5",
"cat ": "4",
"fish ": "12",
}
let obj = {
name: "animal",
children: []
}
for (prop in data) {
let animal = {}
animal[prop.trim()] = Number(data[prop])
obj.children.push(animal)
}
console.log(JSON.stringify(obj))
I've got some data:
var rows = [{
name: "name1",
description: "description1",
value: 101
}, {
name: "name2",
description: "description2",
value: 202
}]
Purely for fun, I'd like to turn this into a matrix of object keys containing arrays of the matching data points. Here's one-liner I got working using forEach():
var o = {}
rows.forEach(row => Object.keys(row).forEach(key => (o[key] === undefined) ? o[key] = [row[key]] : o[key].push(row[key])))
console.log(o)
/*
{
name: ['name1', 'name2'],
description: ['description1', 'description2'],
value: [101, 202]
}
*/
I have a feeling I can still shorten this expression using map() and/or reduce(), but I've so far been completely stymied!
Also, let's assume the keys are consistent, but not always known.
If the keys are consistent, you can do sth like:
var matrix = Object.keys(rows[0]).reduce((o, key) => ( o[key] = rows.map(row => row[key]), o), {});
You could use Array#reduce with a short cut for checking if a property exists.
var rows = [{ name: "name1", description: "description1", value: 101 }, { name: "name2", description: "description2", value: 202 }],
obj = rows.reduce(
(o, row) => (
Object.keys(row).forEach(key => (o[key] = o[key] || []).push(row[key])),
o
),
{}
);
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Using lodash you can do this with
var rows = [{
name: "name1",
description: "description1",
value: 101
}, {
name: "name2",
description: "description2",
value: 202
}];
var combined = _.mergeWith(...rows, (o, s) => _.castArray(o).concat(_.castArray(s)));
console.log(combined);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>