How to exchange the format of arrays? - javascript - javascript

This is my json data:
{
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
My Expected output:
{
"rows": [
{
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
"staffs": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
}
]
},
]
}
I want to exchange the first object into one array as staff, i dont know what kind of library or method is to make this stuff,

Like this? You can use ES 2018 Object spread to pull the properties you want into an object literal.
let a = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
let b = { "rows": [{ ...a.rows[0].login, "staffs": [ { ...a.rows[0] } ] } ] }
delete(b.rows[0].staffs[0].login)
console.log(b)

There are multiple ways to solve this problem. With simple javascript you can do it like this.
var data = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
var exchangedData = data["rows"].map((row) => {
row["id"] = row["login"]["id"]
row["username"] = row["login"]["username"]
row["firstName"] = row["login"]["firstName"]
row["lastName"] = row["login"]["lastName"]
row["code"] = row["login"]["code"]
row["staffs"] = [{ id: row["id"], code: row["code"], position: row["position"], salary: row["salary"]}]
delete row["login"]
delete row["position"]
delete row["salary"]
return row;
})
console.log(exchangedData)

var rows = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
};
var data = {rows:[]}
rows.rows.forEach(function(value, index){
data.rows.push(
_.assign(
{},
{
"id": value.login.id,
"username": value.login.username,
"firstName": value.login.firstName,
"lastName": value.login.lastName,
"code": value.login.code,
},{"staffs":[{"id":value.id, "code":value.code, "position": value.position, "salary": value.salary}]})
)});
console.log(data);

I think this is a much simpler solution that handles any number of objects in your rows array.
result = {
"rows": [
{
"id": 3,
"code": "airtel121",
"position": "manager",
"salary": "25000",
"login": {
"id": 4,
"username": "sameer",
"firstName": "Mohamed",
"lastName": "Sameer",
"code": "airtel121",
}
}
]
}
const data = result.rows.map(d => {
const {id, code, position, salary} = d
return Object.assign(d.login, {staffs: {...{id, code, position, salary}}})
})
console.log(data)

Related

how to push new element to array of objects? [duplicate]

This question already has answers here:
Copy array items into another array
(19 answers)
Closed 10 days ago.
Here i have Array of objects, in this agents array has 0 elements. i have add an object to this. "agents": [{}] in this i want to add below element:
{
"refURL": "/unifiedconfig/config/agentteam/5020",
"changeStamp": 18,
"agentCount": 0,
"description": "Cumulus All Team",
"name": "CumulusAll",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 0,
"agents": [
{}
]
}
I want to add below element to the above in agents array "agents" [{}]
{
"agent": [
{
"refURL": "/unifiedconfig/config/agent/5101",
"agentId": "1300",
"firstName": "Sammy",
"lastName": "Jackson",
"userName": "cgjackson"
},
{
"refURL": "/unifiedconfig/config/agent/5106",
"agentId": "1305",
"firstName": "Angel",
"lastName": "Jolie",
"userName": "cgjolie"
},
{
"refURL": "/unifiedconfig/config/agent/5109",
"agentId": "1308",
"firstName": "Steve",
"lastName": "O",
"userName": "cgsteveo"
}
]
}
This is the final output i want to be achieved
{
"refURL": "/unifiedconfig/config/agentteam/5016",
"changeStamp": 201,
"agentCount": 3,
"description": "Cumulus Finance Team",
"name": "CumulusFinance",
"peripheral": {
"id": 5000,
"name": "CUCM_PG_1"
},
"peripheralId": 5000,
"supervisorCount": 1,
"agents": [
{
"agent": [
{
"refURL": "/unifiedconfig/config/agent/5101",
"agentId": "1300",
"firstName": "Sammy",
"lastName": "Jackson",
"userName": "cgjackson"
},
{
"refURL": "/unifiedconfig/config/agent/5106",
"agentId": "1305",
"firstName": "Angel",
"lastName": "Jolie",
"userName": "cgjolie"
},
{
"refURL": "/unifiedconfig/config/agent/5109",
"agentId": "1308",
"firstName": "Steve",
"lastName": "O",
"userName": "cgsteveo"
}
]
}
],
"supervisors": [
{
"supervisor": [
{
"refURL": "/unifiedconfig/config/agent/5174",
"agentId": "1082",
"firstName": "Rick",
"lastName": "Barrows",
"userName": "rbarrows#dcloud.cisco.com"
}
]
}
]
}
const obj = {"refURL":"/unifiedconfig/config/agentteam/5020","changeStamp":18,"agentCount":0,"description":"Cumulus All Team","name":"CumulusAll","peripheral":{"id":5000,"name":"CUCM_PG_1"},"peripheralId":5000,"supervisorCount":0,"agents":[{}]}
const obj1= {
"agent":[{"refURL":"/unifiedconfig/config/agent/5101","agentId":"1300","firstName":"Sammy","lastName":"Jackson","userName":"cgjackson"},{"refURL":"/unifiedconfig/config/agent/5106","agentId":"1305","firstName":"Angel","lastName":"Jolie","userName":"cgjolie"},{"refURL":"/unifiedconfig/config/agent/5109","agentId":"1308","firstName":"Steve","lastName":"O","userName":"cgsteveo"}]
}
obj.agents.splice(0,1,obj1);
console.log(JSON.stringify(obj))
I replaced answer again, please check.
> Blockquote
You can either do it via expression or side-effect. I'm going to name your object oldObject and your agents object agentsObject.
Expression:
const newObject = {
...oldObject,
agents: [ agentsObject ],
};
Side-effect:
oldObject.agents = [ agentsObject ];

How to flatten this kind of arrays?

I am trying to flatten an array but facing some problem in that. I have this data available to be flattened.
arr = [
{
"data": [
[
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1#test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1",
}
],
[
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
]
}
],
this is what I have.... and I want this data in a way such that it should merge the data in a single array like this below structure
data: [
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1#test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1"},
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
I had tried to use lodash library to flatten it but it didn't work. Any suggestions for this that how can i flatten these arrays to a single array?
You can do this by making use of combination of flatMap and flat(), flat will flatten the inner array and flatMap for the outer array.
var arr = [ { "data": [ [ { "_id": "5ee97ee7f25d1c1482717bdf", "email": "test1#test.io", "profileImages": [], "username": "test1", "birthday": "2020-06-11T10:11:32.000Z", "phoneNumber": "+910000000000", "location": "Test Location", "firstName": "test1", "lastName": "test1", } ], [ { "_id": "5ee97ef2f25d1c1482717be1", "email": "test2#test.io", "profileImages": [], "username": "test2", "birthday": "2020-06-11T10:11:32.000Z", "phoneNumber": "+910000000000", "location": "Test Location" } ] ] }];
var result = arr.flatMap(obj=>obj.data.flat());
console.log(result);
I hope this helps.
flatMap and flat() is not widely supported across all the browser. See this: Search in multidimensional array (Algorithm)
So simple recursion is the safest bet.
var data = [
[
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1#test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1",
}
],
[
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
]
var result = [];
function flatten(data){
data.forEach(k=>{
if(Array.isArray(k)){
flatten(k)
}else{
result.push(k)
}
});
return result;
}
console.log(flatten(data))
you can use flat
var arr = [ { "data": [ [ { "_id": "5ee97ee7f25d1c1482717bdf", "email": "test1#test.io", "profileImages": [], "username": "test1", "birthday": "2020-06-11T10:11:32.000Z", "phoneNumber": "+910000000000", "location": "Test Location", "firstName": "test1", "lastName": "test1", } ], [ { "_id": "5ee97ef2f25d1c1482717be1", "email": "test2#test.io", "profileImages": [], "username": "test2", "birthday": "2020-06-11T10:11:32.000Z", "phoneNumber": "+910000000000", "location": "Test Location" } ] ] }];
console.log([...arr[0].data.flat()])

How to access two data stored in array object that are linked by one field?

I have a REST API from which i am fetching the json data and storing them in array. The API looks like below:
[
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
]
Some of the data have "parent" field.The value in the "parent" field is the "id" of the other data. Now i want to store these data which have reference in the "parent" field of other data in a separate array. For example:
The data with id=101 has "parent" key with value 105 which in turn is the id of the 3rd data.So the data with id=105 should be stored in separate array.
How can i do in a simple and scalable way?
Try
let parents = data.filter(d=> data.some(c=> c.parent==d.id));
let data = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let parents = data.filter(d=> data.some(c=> c.parent==d.id));
console.log(parents);
To have O(2n) complexity first put parents id to some hash table and then filter
let data = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let hash = {};
data.forEach(d=> hash[d.parent]=d);
let parents = data.filter(d=> d.id in hash);
console.log(parents);
You can use map method and store elements into Map collection to have O(1) when you map items:
const maps = new Map(fooArray.map(o=> [o.id, o]))
const result = fooArray.map(({parent, ...rest}) => {
let obj = {...rest};
parent ? (obj.parent = [maps.get(parent)]) : null;
return obj;
})
console.log(result);
An example:
const fooArray = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
]
const maps = new Map(fooArray.map(o=> [o.id, o]))
const result = fooArray.map(({parent, ...rest}) => {
let obj = {...rest};
parent ? (obj.parent = [maps.get(parent)]) : null;
return obj;
})
console.log(result);
You can also collect all parent ids and then find records which has the same id as some parent:
let par_ids = [];
records.forEach(pid =>{
for (let [key, value] of Object.entries(pid)) {
key == 'parent' ? par_ids.push(value) : null;
}
})
let res = records.filter(ob => par_ids.includes(ob.id))
let records = [
{
"id": "100",
"name": "Person1",
"number": "+91-8980439023"
},
{
"id": "102",
"name": "Person2",
"number": "+91-5980339023"
},
{
"id": "105",
"name": "Person3",
"number": "+91-8980439023"
},
{
"id": "101",
"name": "Person4",
"number": "+91-8980439023",
"parent": "105"
},
{
"id": "110",
"name": "Person5",
"number": "+91-8980439023"
},
{
"id": "115",
"name": "Person6",
"number": "+91-9834295899",
"parent": "100"
}
];
let par_ids = [];
records.forEach(pid =>{
for (let [key, value] of Object.entries(pid)) {
key == 'parent' ? par_ids.push(value) : null;
}
})
let res = records.filter(ob => par_ids.includes(ob.id))
console.log(res)

Filter search based on array values in angular 4

I am new in angular 4. While trying to make a search bar got stuck in the logic. So I have a JSON file, and I am trying to search relevant key value pair of that JSON file based on an array values.
My json file :
const trips = {
"20180201": [{
"journeyId": 1001,
"Number": "001",
"DriverName": "Alex",
"Transporter": {
"id": "T1",
"number": "AN01001",
"Company": "Tranzient"
},
"place": [{
"id": 001,
"value": "Washington DC"
},
{
"id": 002,
"value": "Canberra"
}
],
},
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
],
"20180211": [{
"journeyId": 1004,
"Number": "005",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01013",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
},
{
"id": 4,
"value": "Boston"
}
],
},
{
"journeyId": 1005,
"Number": "005",
"DriverName": "Jerry",
"Transporter": {
"id": "T3",
"number": "AN01020",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Ottawa"
}
],
}
],
"20180301": [{
"journeyId": 1006,
"Number": "005",
"DriverName": "demy",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 5,
"value": "Bridgetown"
},
{
"id": 6,
"value": "Vienna"
}
],
}],
};
I have an array
SelectedValues= ["20180201","Vienna"]
All the array values should search depending on the result from its previous array value. For example in this array above, I need to return key value pair of all the places which have its value "Vienna" in date "20180201".
expected output:
trips= {
"20180201": [
{
"journeyId": 1002,
"Number": "001",
"DriverName": "Tom",
"Transporter": {
"id": "T2",
"number": "AN01002",
"Company": "Trax"
},
"place": [{
"id": 2,
"value": "Canberra"
},
{
"id": 4,
"value": "Vienna"
}
],
},
{
"journeyId": 1003,
"Number": "004",
"DriverName": "Jack",
"Transporter": {
"id": "T3",
"number": "AN01003",
"Company": "Trax"
},
"place": [{
"id": 1,
"value": "Washington DC",
}, {
"id": 4,
"value": "Vienna",
}],
}
]
}
So the result returns all the key value pair that have place "Vienna" within the date " 20180201 " .
My solution that I tried to use :
filter(trips, SelectedValues) {
const check = v => options.includes(v) || v && typeof v === 'object' && Object.keys(v).some(l => check(v[l]));
var result = {};
Object.keys(object).forEach(function (k) {
var temp = options.includes(k)
? object[k]
: object[k].filter(check);
if (temp.length) {
result[k] = temp;
}
});
return result;
}
The problem is that it is returning all the key-value pairs that matches all the values in SelectedValues(Implementing OR logic). But I need to implement the array search with AND logic.

How can I access specific value of JSON object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I can't seem to console.log the item name and just that. It's in the position data -> pricing -> tables -> items -> name. I am going for an output that says "Toy Panda".
[
{
"event": "recipient_completed",
"data": {
"id": "msFYActMfJHqNTKH8YSvF1",
"name": "Sample Document",
"status": "document.draft",
"date_created": "2014-10-06T08:42:13.836022Z",
"date_modified": "2016-03-04T02:21:13.963750Z",
"action_date": "2016-09-02T22:26:52.227554",
"action_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed"
},
"created_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"recipients": [
{
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "signer",
"recipient_type": "Signer",
"has_completed": true
}
],
"sent_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"metadata": {
"salesforce_opp_id": "123456",
"my_favorite_pet": "Panda"
},
"tokens": [
{
"name": "Favorite Animal",
"value": "Panda"
}
],
"fields": [
{
"uuid": "YcLBNUKcx45UFxAK3NjLIH",
"name": "Textfield",
"title": "Favorite Animal",
"value": "Panda",
"assigned_to": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "Signer",
"recipient_type": "signer",
"has_completed": true,
"type": "recipient"
}
}
],
"pricing": {
"tables": [
{
"id": 82307036,
"name": "PricingTable1",
"is_included_in_total": true,
"summary": {
"discount": 10,
"tax": 0,
"total": 60,
"subtotal": 60
},
"items": [
{
"id": "4ElJ4FEsG4PHAVNPR5qoo9",
"qty": 1,
"name": "Toy Panda",
"cost": "25",
"price": "53",
"description": "Buy a Panda",
"custom_fields": {
"sampleField": "Sample Field"
},
"custom_columns": {
"sampleColumn": "Sample Column"
},
"discount": 10,
"subtotal": 60
}
],
"total": 60
}
]
},
"tags": [
"test tag",
"sales",
"support"
]
}
}
]
I would really appreciate a tip. Thank you
If you store your JSON object into variable called obj you can access that value ("Toy Panda") with:
obj.data.pricing.tables[0].items[0].name
because tables and items are arrays.
Here is a sample example :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
</script>
Refer this link :[https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/][1]
In your case it should be something like :
var data = // your json;
var json = JSON.parse(data);
console.log(json.pricing.tables.items[0].name;

Categories

Resources