I have an array of objects like the following:
organisationData = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
]
I need to split this array so that it follow the following format:
organisations = [
{
"name": "Apple",
"field": "IT"
},
{
"name": "Microsoft",
"field": "IT"
}
]
I can create a new array that follows the correct format but each 'company' is part of the same array and I'd like to split them out, how do I modify the following?:
let organisationData = [.....]
let organisations = [];
for (org of organisationsData) {
_org = [];
_org[org.key] = org.value;
organisations.push(_org);
};
const organisationData = [
{
id: -516538792,
label: "name",
value: "Apple",
key: "name",
},
{
id: -586565959,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Microsoft",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Amazon",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "IT",
key: "field",
},
{
id: 2081552018,
label: "name",
value: "Dell",
key: "name",
},
{
id: -1094152060,
label: "field",
value: "Laptop Manufacturing",
key: "field",
},
];
let newOrgArray = [];
organisationData.map((m, index) => {
if (index % 2 === 0) {
let orgObj = { name: "", feild: "" };
orgObj["name"] = m.value;
orgObj["feild"] = organisationData[index + 1].value;
newOrgArray.push(orgObj);
}
});
console.log(newOrgArray);
Is this what you trying to achieve :
Data = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
];
result = []
for (var i = 0; i < Data.length; i+=2) {
Temp = {};
Temp[Data[i]['key']] = Data[i]['value'];
Temp[Data[i+1]['key']] = Data[i+1]['value'];
result.push(Temp)
}
console.log(result);
Output :
[ { name: 'Apple', field: 'IT' }, { name: 'Microsoft', field: 'IT' } ]
var organisationData = [
{
"id": -516538792,
"label": "name",
"value": "Apple",
"key": "name"
},
{
"id": -586565959,
"label": "field",
"value": "IT",
"key": "field"
},
{
"id": 2081552018,
"label": "name",
"value": "Microsoft",
"key": "name"
},
{
"id": -1094152060,
"label": "field",
"value": "IT",
"key": "field"
}
];
var organisation = [];
var i = 0;
var temp = '';
organisationData.forEach(function(org){
if(org.key == 'name'){
temp = org.value;
}
if(org.key == 'field'){
organisation[i] = {'name': temp, 'field': org.value};
i++;
}
});
console.log(organisation);
Related
This question already has answers here:
Build tree array from flat array in javascript
(34 answers)
Closed 2 years ago.
I have incoming data in this format:
const worldMap = [
{
"name": "Germany",
"parentId": null,
"type": "Country",
"value": "country:unique:key:1234",
"id": "1",
},
{
"name": "North Rhine",
"parentId": "1",
"type": "State",
"value": "state:unique:key:1234",
"id": "2",
},
{
"name": "Berlin",
"parentId": "1",
"type": "State",
"value": "state:unique:key:1234",
"id": "3",
},
{
"name": "Dusseldorf",
"parentId": "2",
"type": "city",
"value": "city:unique:key:1234",
"id": "4",
},
{
"name": "India",
"parentId": null,
"type": "Country",
"value": "country:unique:key:1234",
"id": "5",
},
];
I want the output to be something like this:
[
{
label: "Germany",
value: "country:unique:key:1234",
subs: [
{
label: "North Rhine",
value: "state:unique:key:1234",
subs: [
{
label: "Dusseldorf",
value: "city:unique:key:1234",
}
]
},
{
label: "Berlin",
value: "state:unique:key:1234",
}
]
}
,
{
"label": "India",
"value": "country:unique:key:1234"
}
]
Basically, it is a three dimensional array with first level being the Countrie, second States and third Cities. I have tried the following code:
let tempCountries = [];
worldMap.map((world) => {
if (world.parentId == null && world.type == "Country") {
tempCountries.push({label: world.name, value: world.value, id: world.id});
}
});
console.log("=== countries ===", tempCountries);
tempCountries.map((tempCountry) => {
const states = worldMap.find((x) => x.parentId == tempCountry.id);
console.log("=== states ===", states);
if (states !== undefined) {
}
});
In the first loop I got all the values for the countries. Next I am trying to append states and cities to the original countries, I got from the first loop. But I am not able to do so. The code should be verbose with minimum number of loops. Could anyone please help achieve this ?
Thanks
You could take a single loop and store all relations between child/parents and parents/childs.
const
data = [{ name: "Germany", parentId: null, type: "Country", value: "country:unique:key:1234", id: "1" }, { name: "North Rhine", parentId: "1", type: "State", value: "state:unique:key:1234", id: "2" }, { name: "Berlin", parentId: "1", type: "State", value: "state:unique:key:1234", id: "3" }, { name: "Dusseldorf", parentId: "2", type: "city", value: "city:unique:key:1234", id: "4" }, { name: "India", parentId: null, type: "Country", value: "country:unique:key:1234", id: "5" }],
tree = ((data, root) => {
var t = {};
data.forEach(({ id, parentId, name: label, value }) => {
Object.assign(t[id] = t[id] || {}, { label, value });
t[parentId] = t[parentId] || {};
(t[parentId].subs = t[parentId].subs || []).push(t[id]);
});
return t[root].subs;
})(data, null);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have Object Like this
var RecuiterInfo = {}
RecruiterInfo.Quote: "1"
RecruiterInfo.CompanyName: "Imperial Innovations",
RecruiterInfo.OrganizationSize: "2",
RecruiterInfo.Person.CitizanZenship: null,
RecruiterInfo.Person.DOB: "Farkhonda#hotmail.com",
RecruiterInfo.Person.Email: "Farkhonda",
RecruiterInfo.Person.FirstName: "FaiZi",
RecruiterInfo.Person.Gender: "4456565656"
RecruiterInfo.Person.LastName: "4456565656",
RecruiterInfo.Person.PhoneNo: "4456565656",
RecruiterInfo.Person.UserId.UserName: "MTIzNDU2",
RecruiterInfo.Person.UserId.Password: null
I want to convert this object to
this specific format Like
{
"QueryObjectID":"RecruiterInfo",
"Values": [
{
"AppFieldID": "Person",
"Value": [
{
"AppFieldID": "CitizanZenship",
"Value": "1"
},
{
"AppFieldID": "DOB",
"Value": "01/01/2019"
},
{
"AppFieldID": "Email",
"Value": "test1#test.com"
},
{
"AppFieldID": "FirstName",
"Value": "test"
},
{
"AppFieldID": "Gender",
"Value": "1"
},
{
"AppFieldID": "LastName",
"Value": "test last"
},
{
"AppFieldID": "PhoneNo",
"Value": "7897897895"
},
{
"AppFieldID": "UserId",
"Value": [
{
"AppFieldID": "UserName",
"Value": "test1#test.com"
},
{
"AppFieldID": "Password",
"Value": "123456"
}
]
}
]
},
{
"AppFieldID": "Quote",
"Value": "Hi Im test"
},
{
"AppFieldID": "CompanyName",
"Value": "Terst"
}
]
}
but it should be a generic/dynamic(I don't want any static stuff here, because in feature there will be a multiple dot/ or nested objects)
I think loop will be based on .(dot),and it will be nested not sure
can any one help me for this json convert
Thanks in advance
You can do it recursively.
const convert = (obj) => {
if (obj === null) return null
if (typeof obj !== 'object') return obj
return Object.entries(obj)
.reduce((acc, [key, value]) => acc.concat({
AppFieldId: key,
Value: convert(value), // Recursive call
}), [])
}
console.log(JSON.stringify(convert(RecruiterInfo), null, 2))
It's not exactly like you want, but you'd need static stuff for that first bit.
[
{
"AppFieldId": "Quote",
"Value": "1"
},
{
"AppFieldId": "CompanyName",
"Value": "Imperial Innovations"
},
{
"AppFieldId": "OrganizationSize",
"Value": "2"
},
{
"AppFieldId": "Person",
"Value": [
{
"AppFieldId": "CitizanZenship",
"Value": null
},
{
"AppFieldId": "DOB",
"Value": "Farkhonda#hotmail.com"
},
{
"AppFieldId": "Email",
"Value": "Farkhonda"
},
{
"AppFieldId": "FirstName",
"Value": "FaiZi"
},
{
"AppFieldId": "Gender",
"Value": "4456565656"
},
{
"AppFieldId": "LastName",
"Value": "4456565656"
},
{
"AppFieldId": "PhoneNo",
"Value": "4456565656"
},
{
"AppFieldId": "UserId",
"Value": [
{
"AppFieldId": "UserName",
"Value": "MTIzNDU2"
},
{
"AppFieldId": "Password",
"Value": null
}
]
}
]
}
]
You could take an iterative approach.
var data = { 'RecruiterInfo.Quote': "1", 'RecruiterInfo.CompanyName': "Imperial Innovations", 'RecruiterInfo.OrganizationSize': "2", 'RecruiterInfo.Person.CitizanZenship': null, 'RecruiterInfo.Person.DOB': "Farkhonda#hotmail.com", 'RecruiterInfo.Person.Email': "Farkhonda", 'RecruiterInfo.Person.FirstName': "FaiZi", 'RecruiterInfo.Person.Gender': "4456565656", 'RecruiterInfo.Person.LastName': "4456565656", 'RecruiterInfo.Person.PhoneNo': "4456565656", 'RecruiterInfo.Person.UserId.UserName': "MTIzNDU2", 'RecruiterInfo.Person.UserId.Password': null },
result = Object.entries(data).reduce((r, [s, v]) => {
var path = s.split('.'),
last = path.pop();
path
.reduce((o, k, i) => {
var temp = o.find(q => q[i ? 'AppFieldID' : 'QueryObjectID'] === k);
if (!temp) o.push(temp = i ? { AppFieldID: k, Value: [] } : { QueryObjectID: k, Values: [] });
return temp[i ? 'Value' : 'Values'];
}, r)
.push({ AppFieldID: last, Value: v });
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
My requirements are very simple: iterate over the array, use the object to determine the selected object, and then push it into the new array, but I don't know how to write it?
Want the result as follows:
[{
key: 'name',
name: "A",
},
{
key: 'note',
name: "C”,
}
]
My code:
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = []
data[0].data.list.map(item => {
data[0].data.show.forEach(prop => {
if (prop !== item.key) {
arr.push({
key: item.key,
name: item.name
})
}
})
})
console.log(arr);
You could check the key if it is not includes in the show property and then push the object.
var data = [{ data: { list: [{ name: "A", key: "name" }, { name: "B", key: "title" }, { name: "C", key: "note" }, { name: "D", key: "desc" }], show: ["title", "desc"] } }],
arr = [];
data[0].data.list.map(({ key, name }) => {
if (!data[0].data.show.includes(key)) {
arr.push({ key, name });
}
});
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try
let d=data[0].data;
let arr= d.list.filter(x=> !d.show.includes(x.key));
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
let d=data[0].data;
let arr= d.list.filter(x=> !d.show.includes(x.key));
console.log(arr);
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = []
data[0].data.list.forEach(keyValue=> !data[0].data.show.includes(keyValue.key) ? arr.push(keyValue): null)
console.log(arr);
var data = [{
"data": {
"list": [{
"name": "A",
"key": "name",
}, {
"name": "B",
"key": "title",
}, {
"name": "C",
"key": "note",
}, {
"name": "D",
"key": "desc",
}],
"show": [
"title",
"desc"
]
}
}]
var arr = data[0].data.list.filter(item => data[0].data.show.every(props => props !== item.key))
console.log(arr);
I need to add an array of objects to an another object whose structure has been shown below.
Here arr is the array of objects that needs to be added to "dest" object.
Help would be appreciated
structure:
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
This array of objects needs to added to an object of following structure:
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
I would want add the fields of "arr" inside "sequence" so that result would something like this:
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
},
{
"field": "state",
"value": "value2",
},
{
"field": "city",
"value": "value3",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
Using forEach() you can do it.
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
arr.forEach(function (item) {
dest.filter.sequence.push(item)
});
console.log(dest)
Also ES6 spread operator can be used to merge
var arr = [
{ field: "state", value: "value2"},
{ field: "city", value: "value3"}
];
var dest = {
"topic": "test",
"filter": {
"sequence": [
{
"field": "country",
"value": "value1",
}
]
},
"order": [
{
"field": "field1",
"order": "backward"
}
]
}
dest.filter.sequence.push(...arr)
console.log(dest)
You just need to use below code to insert array into object.
arr.forEach( function(value, index, array) {
dest.filter.sequence.push(value);
});
Below is the json I have:
{
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
Here I have 2 characteristics object of "test" - A and B.These 2 objects may or may not have "comprisedOf" array. For Eg A has"comprisedOf" array whereas B has not. These comprisedOf array further may or may not have comprisedof objects array.
Now i have to make an array out of this which should be like the given below array:-
[
{
"name": "test",
"children": [
{
"name": "A",
"children": [
{
"name":"A1",
"children:: [
{
"name": "A1.1"
},
{
"name": "A1.2"
}
]
},
{
"name": "A2"
},
{
"name": "A3"
},
{
"name": "A4"
}
]
},
{
"name": "B"
}
]
}
]
How this array can be formed recursively out of the first array?
Thanks so much!!
EDIT:- Here's what I have tried:-
var makeChildrenAll = function(dataChar){
dataChar.forEach(function(char){
if(char.comprisedOf) {
makeChildrenAll(char.comprisedOf);
}
childrenData.push({
name: char.name,
description: char.description,
children: childrenData
});
});
};
makeChildrenAll(dataChar);
In order to be recursive you want the function to return and be able to assign that return to current object
Something like
function mapItems(arr){
// return new array
return arr.reduce((a,c)=>{
var newObj={name:c.name};
if(Array.isArray(c.comprisedOf)){
// use returned array of recursive function to assign to `children` property
newObj.children = mapItems(c.comprisedOf)
}
return a.concat(newObj)
},[])
}
console.log(mapItems(data.characteristics))
.as-console-wrapper { max-height: 100%!important;}
<script>
var data ={
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
</script>
You could take a different start array and use a destructuring for the wanted properties.
function mapItems(array) {
return array.map(({ name, comprisedOf }) =>
Object.assign({ name }, comprisedOf && { children: mapItems(comprisedOf) }));
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES5
function mapItems(array) {
return array.map(function (o) {
var r = { name: o.name };
if (o.comprisedOf) {
r.children = mapItems(o.comprisedOf);
}
return r;
});
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }