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()])
Related
Im trying to filter all the contact I have with an array of numbers I want to remove. This should loop on every contact and remove the numbers not needed. Some contacts have two numbers and only one could be deleted but not the hole contact. I tried already to filter and see if the selected number is in an index but the forEach doesn't seem to be working any advice?. I don't think forEach returns something
const filteredContacts = contacts.filter(contact => numbers.indexOf(contact.phoneNumbers.forEach(phone => phone.number)) > -1);
//2 sample of all contacts
// contacts
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
//numbers not to have
numbers = [
5557664823,
1344043005,
5467865467,
]
//Expected
Object {
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
Object {
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": Array [
Object {
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
]
If I understood right, you want to filter out some numbers from the contact's phone numbers. One solution to this can be approached using Array.map() over the contacts array and replace the phoneNumbers array with a new filtered array. For the filtering procedure we can use Array.filter() and Array.includes() to check if a phone number belong to the list of numbers you want to filter out.
const contacts = [
{
"company": "Financial Services Inc.",
"contactType": "person",
"firstName": "Hank",
"id": "2E73EE73-C03F-4D5F-B1E8-44E85A70F170",
"imageAvailable": false,
"jobTitle": "Portfolio Manager",
"lastName": "Zakroff",
"middleName": "M.",
"name": "Hank M. Zakroff",
"phoneNumbers": [
{
"countryCode": "us",
"digits": "5557664823",
"id": "337A78CC-C90A-46AF-8D4B-6CC43251AD1A",
"label": "work",
"number": "(555) 766-4823",
},
{
"countryCode": "us",
"digits": "7075551854",
"id": "E998F7A3-CC3C-4CF1-BC21-A53682BC7C7A",
"label": "other",
"number": "(707) 555-1854",
},
],
},
{
"contactType": "person",
"firstName": "David",
"id": "E94CD15C-7964-4A9B-8AC4-10D7CFB791FD",
"imageAvailable": false,
"lastName": "Taylor",
"name": "David Taylor",
"phoneNumbers": [
{
"countryCode": "us",
"digits": "5556106679",
"id": "FE064E55-C246-45F0-9C48-822BF65B943F",
"label": "home",
"number": "555-610-6679",
},
],
},
];
// Numbers to filter out.
const numsToFilterOut = [5557664823];
let res = contacts.map(contact =>
{
contact.phoneNumbers = contact.phoneNumbers.filter(
// Unary plus is used to coerces (cast) the string to number.
phone => !numsToFilterOut.includes(+phone.digits)
);
return contact;
});
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
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)
I want to copy employee to a new employee and not point to an old employee.
I try to use:
newEmployees.assign([{}].employees); <br>
newEmployees = [{...employees}]; <br>
They are pointing to an old employee.
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = employees[3]; // assign
employees[3]['firstname'] = 'Arhus'; // change old employees
console.log(newEmployees); //firstname: 'Arhus' - shows employees content
Thank you so much.
Just use spread while assigning the value like this
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = { ...employees[3] };
employees[3]['firstname'] = 'Arhus'; // change employee
console.log(newEmployees); //firstname is still Monkey D
Just use .map and object spread:
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
const newEmployees = employees.map(employee => ({...employee}));
employees[3].firstname = 'Arhus';
console.log(newEmployees[3]);
console.log(employees[3]);
While assigning value you can use Object.assign or Object.clone
Consider the following snippet:
const employees = [
{
"id": "1001",
"firstname": "Luke",
"lastname": "Skywalker",
"company": "Walt Disney",
"salary": "40000"
},
{
"id": "1002",
"firstname": "Tony",
"lastname": "Stark",
"company": "Marvel",
"salary": "1000000"
},
{
"id": "1003",
"firstname": "Somchai",
"lastname": "Jaidee",
"company": "Love2work",
"salary": "20000"
},
{
"id": "1004",
"firstname": "Monkey D",
"lastname": "Luffee",
"company": "One Piece",
"salary": "9000000"
}
];
let newEmployees = [{}];
newEmployees[0] = Object.assign({}, employees[3]);
employees[3]['firstname'] = 'Arhus';
console.log(newEmployees);
I understand you want to copy the object value and don't want to use stringify. Stringifying the object and parsing it back to JSON is one way,
cloning the object is another method and I believe spreading also works.
But if you prefer convenience you may want to take a look at "lodash" library's _.clone and _.clonedeep methods.
Also if you'd like to read more refer :
Lodash .clone and .cloneDeep behaviors
How to copy an object by value, not by reference
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;
I have a HTML code like below which I use AngularJS framework within it:
<select name="choose-staff" ng-model="admin_times[0].user" ng-change="update(reserve.staff)" id="choose-staff">
<option ng-repeat="value in staff | unique:'employee.user.username'" value="{[{ value.employee.user.username }]}">{[{ value.employee.user.first_name }]} {[{ value.employee.user.last_name }]}</option>
</select>
And I get an error like this:
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: value in staff | unique:'employee.user.username', Duplicate key: string:ب, Duplicate value: ب
And if I use track by $index it destroys my desired structure and when I click one of options, the rest of them get vanished.
[
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Haircut",
"fa_title": "کوتاهی مو"
},
"allocated_time": 60,
"booked_no": "XG4OCX81"
},
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 25,
"booked_no": "1AY3F24G"
},
{
"employee": {
"user": {
"id": 2,
"first_name": "رضا",
"last_name": "ولیمرادی",
"user_profile": {
"id": "9d9be03a-f840-46ea-a21e-76cd5775a886",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:10.312340Z",
"location": "36.03133177633187,51.328125"
},
"username": "reza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": false
},
"service": {
"en_title": "Yellow",
"fa_title": "زرد"
},
"allocated_time": 15,
"booked_no": "H989M93X"
},
{
"employee": {
"user": {
"id": 1,
"first_name": "علیرضا",
"last_name": "غفاری",
"user_profile": {
"id": "884b36e3-7bad-466f-afee-25801572b834",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:39.522362Z",
"location": "32.24997445586331,53.26171875"
},
"username": "alireza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 20,
"booked_no": "O5KLFPZB"
}
]
I don't like the redundancy of employee.user.username
Looks to me like the unique value in each object is the booked_no.
In which case you should use track by value.booked_no