Convert object to array of objects using javascript - javascript

I would like to convert an object of the following format :
{ From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} }
I wanted to convert this array:
[
{from: "A" ,to: "A1" , value: 1 },
{from: "B" ,to: "B1" , value: 2},
{from: "C" ,to: "C1" , value: 3 }
]
How I can convert it in javascript code ?

The input you have given is wrong because it contains array with key:value pairs and object without key:value. It should be
{ From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }
Now to convert to desired result you can use map()
let obj = { From: ["A","B","C"], To:["A1","B1","C1"], value: [1,2,3] }
let res = obj.From.map((form,i) => {
let value = obj.value[i];
let to = obj.To[i];
return {form,to,value}
})
console.log(res)

Related

How to insert an object into an array which is inside an object?

Suppose if we are having data like this, how can we use dot notations or anything to update the array(data2) inside the object data1 which is inside the array(data).
data = [
data1:
{
a:"1",
b:"2"
}
]
// another array(data2 - below) I am having I have to push that array inside
data1 as an object
data2 = [
{
c:"3"
},
{
d:"4"
}
]
The response I want as below:
data = [
data1:
{
a:"1",
b:"2"
},
data2 = [
{
c:"3"
},
{
d:"4"
}
]
]
var array = [];
array['data1'] = { 'name': 'a' }
var array2 = [{ c: 3 }, { d: 4 }];
array['data2'] = array2;
console.log(array)
OutPut:
[ data1: { name: 'a' }, data2: [ { c: 3 }, { d: 4 } ] ]
I didnt really understand your question but i think this is what you want?!
data = {
data1:
{
a: "1",
b: "2"
}
}
data2 = [
{
c: "3"
},
{
a: "3"
},
{
d: "4"
}
]
for (var key in data2) {
for (var key2 in data2[key]) {
if(data.data1[key2] != null){
console.log("data.data1 with they key" + key2 + " could have been replaced/updated with " + data2[key][key2]);
}
console.log("key " + key2 + " has value " + data2[key][key2]);
}
}
Result:
key c has value 3
data.data1 with they keya could have been replaced/updated with 3
key a has value 3
key d has value 4
Edit:
Why dont you just do
data["data2"] = data2?
I tried on myself and I got the solution. If we have to make another field in an object you just give a name like this
data.dataTwo
this will create another field with new name and now if we want to transfer or store an array in this we can simply do this
data.dataTwo = data2
This will assign that data2 named array in a new field what is given as dataTwo

Change the nested array object by passing parameter in javascript

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

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

how to loop over array of objects to filter out based on another array of strings

I have an array of objects and an array of string. I need to remove certain elements from the array of string based on the value in the objects.
And this needs to happen in the render method in react.
this.state.pillarNames.forEach(pillarName =>
(pillarData.find(pillar =>
pillar.name === pillarName) === undefined ?
<MenuItem
style={{ fontSize: '14px'
value={pillarName}
key={pillarName}
name={pillarName}
></MenuItem> : null
)
)
I have tried something like this and is not working.
pillarNames = ["abc", "xyz", "def", "hij"];
pillarData = [{
name: "abc",
value: 1
}, {
name: "xyz",
value: 2
}];
So, I need only "def" and "hij" from pillarNames. How do i go about this?
You can chain Array.prototype.filter() to filter and then with the result array Array.prototype.forEach():
const pillarNames = ["abc", "xyz", "def", "hij"]
const pillarData = [{name: "abc", value: 1}, {name: "xyz", value: 2}]
// ...
pillarNames.filter(pn => pillarData.find(pd => pd.name === pn)).forEach(pn => /* your logic... */)

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

Categories

Resources