Related
I'm importing data from my crm Pipedrive into Google sheets using Google Apps Script. This is part of a larger process but I'm at an impasse with this section of the script. I need to return a value by matching two parts of one array to another array.
First I pull all deal fields, which returns custom field keys and their id/label pairs. Here's a simplified output example:
{
"success": true,
"data": [
{
"id": 12500,
"key": "c4ecbe01c34994ede3a50c0f8",
"name": "Lead Type",
"options": [
{
"label": "Expired",
"id": 28
},
{
"label": "Sale",
"id": 29
},
{
"label": "Rent",
"id": 30
},
{
"label": "Other",
"id": 31
}
],
"mandatory_flag": false
}
]
}
Then I have separate info from a specific deal that includes an id. I need to match the below id 28 to the above array and return the label Expired:
var leadType = dealresponse.data["c4ecbe01c34994ede3a50c0f8"];
which returns 28
I don't know what '28' means so that's why I need to match it to the label Expired.
The dealFields array is long, maybe 50 or 100 of the above array objects. And there are around 10 custom deal field keys where I will have to return the label base on matching the key and id. I think I have to loop each key and id to return the label. But not sure of the optimum way to do this and save on processing power.
I tried:
for (var i in dealFieldsresponse) {
if (dealFieldsresponse[i].data.key == "c4ecbe01c34994ede3a50c0f8") {
for (var j in dealFieldsresponse[j]) {
if (dealFieldsresponse[j].id == "28") {
Logger.log(dealFieldsresponse[j].label);
}
}
}
}
It's not working. I'm new at javascript and programming in general so this is my best guess and I appreciate any insights.
Edit: here's a bigger chunk of code that I have to work with:
// Get deal fields data
var dealFieldsurl = URL +'/v1/dealFields?api_token='+ API_TOKEN;
var options = {
"method": "get",
"contentType": "application/json",
};
var dealFieldsresponse = UrlFetchApp.fetch(dealFieldsurl, options);
dealFieldsresponse = JSON.parse(dealFieldsresponse.getContentText());
// Get deal data
var dealurl = URL +'/v1/deals/' + dealId + '?api_token='+ API_TOKEN;
var options = {
"method": "get",
"contentType": "application/json",
};
var dealresponse = UrlFetchApp.fetch(dealurl, options);
dealresponse = JSON.parse(dealresponse.getContentText());
var propertyAddress = dealresponse.data["9bd1d8c4f07f5795fd8bffb16f3b63c6547d7d3a"];
var leadType = dealresponse.data["c4ecbe01c3494d1be52432f4a3194ede3a50c0f8"];
var dealType = dealresponse.data["a4269fb4730cf7fd1787752be94eacbc4b0de24e"];
var dealSource = dealresponse.data["d76fa2d6f8454a51f7d64d981cd9320877bc2ea0"];
var marketingFor = dealresponse.data["58cb55090b55652b7f89a8b44074682d874c548a"];
var dateListedOnMarket = dealresponse.data["aa49c7b95a7d151bec4c2d936f6ab40d0caea43c"];
var dateTakenOffMarket = dealresponse.data["660c1250b0a641a10ff9121c2df124ff89c13052"];
var askingPrice = dealresponse.data["1de94dbf589fda7a3a3248662cd24f03d512a961"];
And the dealFieldsresponse variable stores an array with many objects containing arrays. Here are two primary objects, as you can see each has a key and then options. I need to match the key and then find the id within options for each key
{
"id": 12500,
"key": "c4ecbe01c3494d1be52432f4a3194ede3a50c0f8",
"name": "Lead Type",
"order_nr": 64,
"field_type": "set",
"add_time": "2020-08-20 19:33:22",
"update_time": "2020-08-20 19:33:22",
"last_updated_by_user_id": 11678191,
"active_flag": true,
"edit_flag": true,
"index_visible_flag": true,
"details_visible_flag": true,
"add_visible_flag": true,
"important_flag": true,
"bulk_edit_allowed": true,
"searchable_flag": false,
"filtering_allowed": true,
"sortable_flag": true,
"options": [
{
"label": "Expired",
"id": 28
},
{
"label": "Sale",
"id": 29
},
{
"label": "Rent",
"id": 30
},
{
"label": "Other",
"id": 31
}
],
"mandatory_flag": false
},
{
"id": 12502,
"key": "a4269fb4730cf7fd1787752be94eacbc4b0de24e",
"name": "Deal Type",
"order_nr": 65,
"field_type": "set",
"add_time": "2020-08-20 19:57:12",
"update_time": "2020-08-20 19:57:12",
"last_updated_by_user_id": 11678191,
"active_flag": true,
"edit_flag": true,
"index_visible_flag": true,
"details_visible_flag": true,
"add_visible_flag": true,
"important_flag": true,
"bulk_edit_allowed": true,
"searchable_flag": false,
"filtering_allowed": true,
"sortable_flag": true,
"options": [
{
"label": "Lease",
"id": 37
},
{
"label": "Financing",
"id": 38
},
{
"label": "Assign",
"id": 39
},
{
"label": "ST",
"id": 40
},
{
"label": "Other (see notes)",
"id": 41
}
],
"mandatory_flag": false
},
Edit 2: how do I return the labels for multiple ids?
const obj = {
"a4269fb4730cf7fd1787752be94eacbc4b0de24e": {id: 37,38}, "58cb55090b55652b7f89a8b44074682d874c548a": {id: 44,45},
"2ec54cce0d091b69b1fd1a245c7aad02b57cadb8": {id: 126},
"fab84c732295022ecd7bdf58892a62cb4d8ecf24": {id: 50,52,54},
};
For example, I'd want the first to return red, blue as a string, and the second to return green, orange as a string. Assuming the labels that match the ids are colors. The third one only has one id, but the fourth one has three. How do I account for this? And I'd like my output to be some kind of array where I can then say search key a4269fb4730cf7fd1787752be94eacbc4b0de24e and return value red, blue as a string
I believe your goal as follows.
You want to retrieve the value of label using key and id from the JSON object in your question using Google Apps Script.
As a sample situation, you want to retrieve the value of "label": "Expired" using "key": "c4ecbe01c34994ede3a50c0f8" and "id": 28.
The JSON object has the arrays of data and options. Both arrays have the several elements.
Modification points:
If dealFieldsresponse is the JSON object in your question, dealFieldsresponse.data and dealFieldsresponse.data[].options are 1 dimensional array. When you want to retrieve the value of key and id, it is required to loop those arrays.
When above points are reflected to your script, it becomes as follows.
Modified script:
const searchKey = "c4ecbe01c34994ede3a50c0f8"; // Please set the value of key.
const searchId = 28; // Please set the value of id.
const dealFieldsresponse = {
"success": true,
"data": [
{
"id": 12500,
"key": "c4ecbe01c34994ede3a50c0f8",
"name": "Lead Type",
"options": [
{
"label": "Expired",
"id": 28
},
{
"label": "FSBO",
"id": 29
},
{
"label": "FRBO",
"id": 30
},
{
"label": "Other",
"id": 31
}
],
"mandatory_flag": false
}
]
};
const data = dealFieldsresponse.data;
for (let i = 0; i < data.length; i++) {
if (data[i].key == searchKey) {
const options = data[i].options;
for (let j = 0; j < options.length; j++) {
if (options[j].id.toString() == searchId.toString()) {
// Logger.log(options[j].label);
console.log(options[j].label);
}
}
}
}
Other sample:
As other sample script, how about the following script? In this sample, the result values are put in an array.
const searchKey = "c4ecbe01c34994ede3a50c0f8"; // Please set the value of key.
const searchId = 28; // Please set the value of id.
const dealFieldsresponse = {
"success": true,
"data": [
{
"id": 12500,
"key": "c4ecbe01c34994ede3a50c0f8",
"name": "Lead Type",
"options": [
{
"label": "Expired",
"id": 28
},
{
"label": "FSBO",
"id": 29
},
{
"label": "FRBO",
"id": 30
},
{
"label": "Other",
"id": 31
}
],
"mandatory_flag": false
}
]
};
const res = dealFieldsresponse.data.reduce((ar, {key, options}) => {
if (key == searchKey) {
options.forEach(({id, label}) => {
if (id == searchId) ar.push(label);
});
}
return ar;
}, []);
console.log(res)
Added:
When you want to retrieve the multiple values using the multiple key and id, how about the following sample script? In this sample script, the key c4ecbe01c34994ede3a50c0f8 and id 28 and the key a4269fb4730cf7fd1787752be94eacbc4b0de24e and id 37 are searched and the values of label are retrieved.
const obj = {
"c4ecbe01c34994ede3a50c0f8": {id: 28},
"a4269fb4730cf7fd1787752be94eacbc4b0de24e": {id: 37}
}; // Please set the key and id you want to search.
const dealFieldsresponse = {
"success": true,
"data": [
{
"id": 12500,
"key": "c4ecbe01c34994ede3a50c0f8",
"name": "Lead Type",
"options": [
{
"label": "Expired",
"id": 28
},
{
"label": "FSBO",
"id": 29
},
{
"label": "FRBO",
"id": 30
},
{
"label": "Other",
"id": 31
}
],
"mandatory_flag": false
}
]
};
dealFieldsresponse.data.forEach(({key, options}) => {
if (obj[key]) {
options.forEach(({id, label}) => {
if (id == obj[key].id) obj[key].label = label;
});
}
});
console.log(obj)
Result:
When above script is run, the following result is obtained.
{
"c4ecbe01c34994ede3a50c0f8":{"id":28,"label":"Expired"},
"a4269fb4730cf7fd1787752be94eacbc4b0de24e":{"id":37}
}
At above sample JSON object, the label of the key c4ecbe01c34994ede3a50c0f8 and id 28 is retrieved.
I have an array like the one shown below. I need to limit the number of objects in the array with ord:1 to 5. How can I to limit the number of objects inside an array based on ord property?
[{"id":"typeahead-86-4951-option-0","label":"Spigen Samsung GS5
Case","model":{"ord":1,"short_description":"Samsung Galaxy S5"}},
{"id":"typeahead-86-4951-option-1","label":"Spigen iPhone 5/5s
Case","model":{"ord":1,"short_description":"iPhone 5 and 5s"}},
{"id":"typeahead-86-4951-option-2","label":"Earphones","model":
{"ord":1,"short_description":"Buy earphones"}},
{"id":"typeahead-86-4951-option-5","label":"Web Conferencing","model":
{"ord":1,"short_description":"Request"}},
{"id":"typeahead-86-4951-option-6","label":"Dreamweaver","model":
{"ord":1,"short_description":null}},
{"id":"typeahead-86-4951-option-7","label":"SSL Certification","model":
{"ord":1,"short_description":"Do you need to update"}},
{"id":"typeahead-86-4951-option-8","label":"Access","model":
{"ord":1,"short_description":"Microsoft Access"}},
{"id":"typeahead-86-4951-option-9","label":"Fireworks","model":
{"ord":1,"short_description":"Adobe Systems Fireworks"}},
{"id":"typeahead-86-4951-option-10","label":"Spigen iPhone 6 Case","model":
{"ord":1,"short_description":"For iPhone 6"}},
{"id":"typeahead-86-4951-option-11","label":"What is a cookie?
\t\t","model":{"ord":4,"short_description":"What is a cookie?\t\t"}},
{"id":"typeahead-86-4951-option-12","label":"What are phishing scams and
how can I avoid them?\n\t\t","model":{"ord":4,"short_description":"What
are phishing"}},
{"id":"typeahead-86-4951-option-13","label":"How to Deal with
Spam","model":{"ord":4,"short_description":"How to Deal with Spam"}},
{"id":"typeahead-86-4951-option-14","label":"What is Spam?","model":
{"ord":4,"short_description":"What is Spam?}},
{"id":"typeahead-86-4951-option-15","label":"How to set\n\t\t","model":
{"ord":4,"short_description":"How\n\t\t"}}
]
You can create dictionary with ord values as keys and store there up to 5 items.In the end just concat all arrays in dictionary.
let input = [{
"id": "typeahead-86-4951-option-0",
"label": "Spigen Samsung GS5 Case",
"model": {
"ord": 1,
"short_description": "Samsung Galaxy S5"
}
}, {
"id": "typeahead-86-4951-option-1",
"label": "Spigen iPhone 5/5s Case",
"model": {
"ord": 1,
"short_description": "iPhone 5 and 5s"
}
},
{
"id": "typeahead-86-4951-option-2",
"label": "Earphones",
"model": {
"ord": 1,
"short_description": "Buy earphones"
}
},
{
"id": "typeahead-86-4951-option-5",
"label": "Web Conferencing",
"model": {
"ord": 1,
"short_description": "Request"
}
},
{
"id": "typeahead-86-4951-option-6",
"label": "Dreamweaver",
"model": {
"ord": 1,
"short_description": null
}
},
{
"id": "typeahead-86-4951-option-7",
"label": "SSL Certification",
"model": {
"ord": 1,
"short_description": "Do you need to update"
}
},
{
"id": "typeahead-86-4951-option-8",
"label": "Access",
"model": {
"ord": 1,
"short_description": "Microsoft Access"
}
},
{
"id": "typeahead-86-4951-option-9",
"label": "Fireworks",
"model": {
"ord": 1,
"short_description": "Adobe Systems Fireworks"
}
},
{
"id": "typeahead-86-4951-option-10",
"label": "Spigen iPhone 6 Case",
"model": {
"ord": 1,
"short_description": "For iPhone 6"
}
},
{
"id": "typeahead-86-4951-option-11",
"label": "What is a cookie?\t\t",
"model": {
"ord": 4,
"short_description": "What is a cookie?\t\t"
}
},
{
"id": "typeahead-86-4951-option-12",
"label": "What are phishing scams and how can I avoid them?\n\t\t",
"model": {
"ord": 4,
"short_description": "What are phishing"
}
},
{
"id": "typeahead-86-4951-option-13",
"label": "How to Deal with Spam",
"model": {
"ord": 4,
"short_description": "How to Deal with Spam"
}
},
{
"id": "typeahead-86-4951-option-14",
"label": "What is Spam?",
"model": {
"ord": 4,
"short_description": "What is Spam?"
}
},
{
"id": "typeahead-86-4951-option-15",
"label": "How to set\n\t\t",
"model": {
"ord": 4,
"short_description": "How\n\t\t"
}
}
],
ordObj;
ordObj = input.reduce(function(acc, el) {
let ord = el.model.ord;
if (!acc.hasOwnProperty(ord)) {
acc[ord] = [];
}
if (acc[ord].length < 5) {
acc[ord].push(el);
}
return acc;
}, {});
let result = Object.values(ordObj).reduce((acc, el) => (acc.concat(el)), []);
console.log(result);
You can use a small loop like this, counting how many "ord":1 you keep, and stopping after 5 :
let input = [
{"id":"typeahead-86-4951-option-0","label":"Spigen Samsung GS5 Case","model":{"ord":1,"short_description":"Samsung Galaxy S5"}}, {"id":"typeahead-86-4951-option-1","label":"Spigen iPhone 5/5s Case","model":{"ord":1,"short_description":"iPhone 5 and 5s"}},
{"id":"typeahead-86-4951-option-2","label":"Earphones","model": {"ord":1,"short_description":"Buy earphones"}},
{"id":"typeahead-86-4951-option-5","label":"Web Conferencing","model": {"ord":1,"short_description":"Request"}},
{"id":"typeahead-86-4951-option-6","label":"Dreamweaver","model": {"ord":1,"short_description":null}},
{"id":"typeahead-86-4951-option-7","label":"SSL Certification","model":{"ord":1,"short_description":"Do you need to update"}},
{"id":"typeahead-86-4951-option-8","label":"Access","model": {"ord":1,"short_description":"Microsoft Access"}},
{"id":"typeahead-86-4951-option-9","label":"Fireworks","model": {"ord":1,"short_description":"Adobe Systems Fireworks"}},
{"id":"typeahead-86-4951-option-10","label":"Spigen iPhone 6 Case","model": {"ord":1,"short_description":"For iPhone 6"}},
{"id":"typeahead-86-4951-option-11","label":"What is a cookie?\t\t","model":{"ord":4,"short_description":"What is a cookie?\t\t"}},
{"id":"typeahead-86-4951-option-12","label":"What are phishing scams and how can I avoid them?\n\t\t","model": {"ord":4,"short_description":"What are phishing"}},
{"id":"typeahead-86-4951-option-13","label":"How to Deal with Spam","model":{"ord":4,"short_description":"How to Deal with Spam"}},
{"id":"typeahead-86-4951-option-14","label":"What is Spam?","model": {"ord":4,"short_description":"What is Spam?"}},
{"id":"typeahead-86-4951-option-15","label":"How to set\n\t\t","model": {"ord":4,"short_description":"How\n\t\t"}}
],
output = [],
count = 0;
input.forEach( obj => {
if(obj.model.ord===1){
if(count>=5) return
count++
}
output.push(obj)
})
console.log("Count before : " + input.filter(o=>o.model.ord===1).length )
console.log("Count after : " + output.filter(o=>o.model.ord===1).length )
To achieve expected result, use filter methos to filter out order:1 records and slice array methods to get first 5
let final = arr.filter(v => v.model.ord === 1).slice(0, 5);
codepen - https://codepen.io/nagasai/pen/NOmXar?editors=1010
let arr = [{"id":"typeahead-86-4951-option-0","label":"Spigen Samsung GS5 Case","model":{"ord":1,"short_description":"Samsung Galaxy S5"}},
{"id":"typeahead-86-4951-option-1","label":"Spigen iPhone 5/5s Case","model":{"ord":1,"short_description":"iPhone 5 and 5s"}},
{"id":"typeahead-86-4951-option-2","label":"Earphones","model":
{"ord":1,"short_description":"Buy earphones"}},
{"id":"typeahead-86-4951-option-5","label":"Web Conferencing","model":
{"ord":1,"short_description":"Request"}},
{"id":"typeahead-86-4951-option-6","label":"Dreamweaver","model":
{"ord":1,"short_description":null}},
{"id":"typeahead-86-4951-option-7","label":"SSL Certification","model":
{"ord":1,"short_description":"Do you need to update"}},
{"id":"typeahead-86-4951-option-8","label":"Access","model":
{"ord":1,"short_description":"Microsoft Access"}},
{"id":"typeahead-86-4951-option-9","label":"Fireworks","model":
{"ord":1,"short_description":"Adobe Systems Fireworks"}},
{"id":"typeahead-86-4951-option-10","label":"Spigen iPhone 6 Case","model":
{"ord":1,"short_description":"For iPhone 6"}},
{"id":"typeahead-86-4951-option-11","label":"What is a cookie? \t\t","model":{"ord":4,"short_description":"What is a cookie?\t\t"}},
{"id":"typeahead-86-4951-option-12","label":"What are phishing scams and how can I avoid them?\n\t\t","model":{"ord":4,"short_description":"What are phishing"}},
{"id":"typeahead-86-4951-option-13","label":"How to Deal with Spam","model":{"ord":4,"short_description":"How to Deal with Spam"}},
{"id":"typeahead-86-4951-option-14","label":"What is Spam?","model": {"ord":4,"short_description":"What is Spam?"}},
{"id":"typeahead-86-4951-option-15","label":"How to set\n\t\t","model": {"ord":4,"short_description":"How\n\t\t"}}]
let final = arr.filter(v => v.model.ord === 1).slice(0, 5);
console.log(final)
You can create something similar to what I below as tracker. Use that variable to keep a count of items by ord. In my example below, I am using Array.prototype.filter on your original array of data below. Each time the callback encounters an array element with an ord property equal to five, the tracker count is incremented. If the count is less than 5 we can add it to our new array, if not, skip it.
var tracker = (function(i) {
var c = i;
return {
value: () => c,
increment: () => c += 1,
decrement: () => c -= 1
}
})(0);
var data = [{
id: 'item0',
ord: 1
}, {
id: 'item1',
ord: 1
}, {
id: 'item2',
ord: 1
}, {
id: 'item3',
ord: 1
}, {
id: 'item4',
ord: 1
}, {
id: 'item5',
ord: 1
}, {
id: 'item6',
ord: 1
}, {
id: 'item7',
ord: 1
}, {
id: 'item8',
ord: 1
}, {
id: 'item9',
ord: 2
}, {
id: 'item10',
ord: 2
}, {
id: 'item11',
ord: 2
}, {
id: 'item12',
ord: 2
}];
var limited = data.filter(el => {
if (el.ord === 1) {
tracker.increment();
if (tracker.value() < 6) {
return true;
}
return false;
}
return true;
});
console.log(limited);
I have this sample JSON object
var sample = [{
"label": "one",
"value": 1
}, {
"label": "two",
"value": 2
}, {
"label": "three",
"value": 3
}, {
"label": "four",
"value": 4
}, {
"label": "five",
"value": 5
}];
I want to change it some thing like this
var sample = [{
"label": "one",
"value": 1,
"newKeyValue": "one|1"
}, {
"label": "two",
"value": 2,
"newKeyValue": "two|2"
}, {
"label": "three",
"value": 3,
"newKeyValue": "three|3"
},
...
];
It should combine both key values and return new key value combining both.
JSON is coming dynamically key label and value are not static it can be anything. For example [{"name":"srinivas","lastname":"pai"}]
You can use map like this :
EDIT
For handling generic keys you can use
Object.keys(d)[0] for first key
Object.keys(d)[1] for second key
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
var data = sample.map(function(d){
return {label: Object.keys(d)[0], value: Object.keys(d)[1], newKeyValue: Object.keys(d)[0] +"|" + Object.keys(d)[1]}
})
console.log(data)
Hope this helps!
You can use Array#map(), Object.keys(), and Array#join().
In ES6, you can use Arrow functions.
sample = sample.map(obj => {
var keys = Object.keys(obj);
obj.newKeyValue = keys.map(key => obj[key]).join('|');
return obj;
});
var sample = [{
"label": "one",
"value": 1
}, {
"name": "two",
"age": 2
}, {
"five": "three",
"six": 3
}, {
"company": "four",
"organization": 4
}, {
"label": "five",
"value": 5
}];
sample = sample.map(function (x) {
var keys = Object.keys(x);
x.newKeyValue = keys.map(key => x[key]).join('|');
return x;
});
console.log(sample);
document.body.innerHTML = '<pre>' + JSON.stringify(sample, 0, 4) + '</pre>';
In ES5, you can use the same code with anonymous functions
sample = sample.map(function (obj) {
var keys = Object.keys(obj);
obj.newKeyValue = keys.map(function (key) {
return obj[key]
}).join('|');
return obj;
});
Limitations due to dynamic keys:
The order of the keys in object cannot be maintained
This will join all the available keys in the object (in case if you just want to join fewer)
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2,
"optionalValue":2
},
{
"label":"three",
"value":3,
"remarks":"free text"
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
for (var key in sample) {
var newValue = [];
for (var piece in sample[key]){
newValue.push(sample[key][piece])
}
sample[key]["newKeyValue"] = newValue.join('|');
}
$('pre').html(JSON.stringify(sample,null,4));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre></pre>
You can use Array.prototype.forEach() for in situ changes.
The forEach() method executes a provided function once per array element.
Edit: with dynamic keys, stored in an array, because of the order.
var sample = [{ "label": "one", "value": 1 }, { "label": "two", "value": 2 }, { "label": "three", "value": 3 }, { "label": "four", "value": 4 }, { "label": "five", "value": 5 }];
sample.forEach(function (a) {
a.newKeyValue = ['label', 'value'].map(function (k) { return a[k]; }).join('|');
});
document.write('<pre>' + JSON.stringify(sample, 0, 4) + '</pre>');
If more element are their then use $.extend
var sample = [
{
"label":"one",
"value":1
},
{
"label":"two",
"value":2
},
{
"label":"three",
"value":3
},
{
"label":"four",
"value":4
},
{
"label":"five",
"value":5
}
];
$(sample).each(function(i,item){
var keyes = Object.keys(item);
sample[i] = $.extend(item,{newKeyValue: item[keyes[0]] +"|" +item[keyes[1]]});
});
console.log(sample)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$.extend also helpful when you are having more objects already and you want to merge both
eg.
var base = {
"label":"one",
"value":1
}
and you want to add more objects
var extra = {
"new1":"value1",
"new2":"value2",
"new3":"value3",
"new4":"value4",
}
then it will be done by
$.extend(base,extra);
Output:
{
"label":"one",
"value":1,
"new1":"value1",
"new2":"value2",
"new3":"value3",
"new4":"value4",
}
var sample = [{"name":"srinivas","lastname":"pai"}];
sample.map(function(item) {
item.newKeyValue = Object.getOwnPropertyNames(item).map(function(d) {return item[d];}).join("|");
})
console.log(sample);
This is my saved localstorage,
[{"industry_Id":1,"merchant_id":2}]
I want to filter below result, to get HP.
{
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
}
I thought of using multiple $.each but it have to iterate few times and it's quite redundant.
I would prefer using Javascript for loop, that way you can skip iterating over every object once required element is found.
Without jQuery (using for)
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
With jQuery (using $.each)
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
var arg = [{"industry_Id":1,"merchant_id":2}];
var data = {
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
};
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
console.log(merchant);
document.writeln("<b>Without jQuery:</b><br>");
document.writeln((merchant !== null) ? "Found " + merchant['name'] : "Not found");
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
console.log(merchant_found);
document.writeln("<br><br><b>With jQuery:</b><br>");
document.writeln((merchant_found) ? "Found " + merchant_found['name'] : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
selectors.map(function(selector) {
return data.industries.filter(function(industry) {
return industry.id == selector.industry_Id;
})[0].merchant.filter(function(merchant) {
return merchant.id == selector.merchant_id;
})[0].name;
});
// => DEF
If you want "HP", you want industry 2, not industry 1.
.filter(...)[0] is not really optimal. You could use .find(...), but that is not yet universally supported. Or you could use plain old JavaScript and write for loops instead to make it fast. Or you could use objects with ID keys instead of arrays to make lookups faster.
When it comes into a position where collection of data is what you're processing, I suggest you to take a look at underscore.js. It's not optimal choice for the best performance but it does make you code more readable and makes more sense especially when compared with loop.
Say data is a variable which stores your JSON data.
Try this:
// Given this selector criteria
var select = [{"industry_Id":1,"merchant_id":2}];
function filterByCriteria(criteria, data){
var match = [];
_.each(criteria, function(crit){
function matchIndustry(rec){ return rec.id===crit.industry_Id }
function matchMerchant(rec){ return rec.id===crit.merchant_id }
// Filter by industry id
var industry = _.first(_.where(data.industry, matchIndustry));
// Filter by merchant id
var merchant = _.where(industry.merchant, matchMerchant);
_.each(merchant, function addToMatchResult(m){
match.push(m.name);
});
});
return match;
}
var filteredData = filterByCriteria(select, data);
From snippet above, any merchants which match the search criteria will be taken to the match list. Is it more readable to you?
Do you even need numerical id's? Gets super easy when you don't.
/*
{
"industry": {
"oil and gas":{
"merchant": {
"ABC": {
"name": "ABC oil"
},
"DEF": {
"name": "DEF gas"
},
"GHJ" :{
"name": "GHJ oil and gas"
}
}
},
"IT": {
"merchant": {
"Apple" : {
"name": "Apple computers"
},
"HP": {
"name": "Hewlett Packard"
},
"Google": {
"name": "Google. Maw haw haw"
}
}
}
}
}
*/
var data = '{"industry": {"oil and gas":{"merchant": {"ABC": {"name": "ABC oil"},"DEF": {"name": "DEF gas"},"GHJ" :{"name": "GHJ oil and gas"}}},"IT": {"merchant": {"Apple" : {"name": "Apple computers"},"HP": {"name": "Hewlett Packard"},"Google": {"name": "Google. Maw haw haw"}}}}}';
data = JSON.parse(data);
var merchant = data.industry['IT'].merchant['HP'];
alert(merchant.name);
//console.log(merchant.name);
When I console.log on a variable called "source" I get the following:
[Object {
name = "Yahoo", value = "yahoo"
},
Object {
name = "yahtzee", value = "yahtzee"
},
Object {
name = "Yakov Smirnoff", value = "yakov-smirnoff"
},
Object {
name = "Yarbrough", value = "yarbrough"
},
Object {
name = "yard sales", value = "yard-sales"
},
Object {
name = "yarmulke", value = "yarmulke"
},
Object {
name = "yawning", value = "yawning"
},
Object {
name = "Yeah Yeah Yeahs", value = "yeah-yeah-yeahs"
},
Object {
name = "Yeardly Smith", value = "yeardly-smith"
},
Object {
name = "YearOne", value = "yearone"
},
Object {
name = "Yeasayer", value = "yeasayer"
},
Object {
name = "yelle", value = "yelle"
},
Object {
name = "yelling", value = "yelling"
},
Object {
name = "yellowpages", value = "yellowpages"
},
Object {
name = "yellowstone", value = "yellowstone"
},
Object {
name = "yemen", value = "yemen"
},
Object {
name = "Yeoman", value = "yeoman"
},
Object {
name = "Yes Dear", value = "yes-dear"
},
Object {
name = "Yes Men", value = "yes-men"
},
Object {
name = "yeti", value = "yeti"
},
Object {
name = "yiddish", value = "yiddish"
},
Object {
name = "ymca", value = "ymca"
},
Object {
name = "yodeling", value = "yodeling"
},
Object {
name = "yoga", value = "yoga"
},
Object {
name = "yogurt", value = "yogurt"
},
Object {
name = "Yoko Ono", value = "yoko-ono"
},
Object {
name = "Yo-Landi Vi$$er", value = "yo-landi-vier"
},
Object {
name = "yo momma", value = "yo-momma"
},
Object {
name = "YONKERS", value = "yonkers"
},
Object {
name = "yosemite", value = "yosemite"
},
Object {
name = "yoshimoto", value = "yoshimoto"
},
Object {
name = "Yoshio Yoda", value = "yoshio-yoda"
},
Object {
name = "you got served", value = "you-got-served"
},
Object {
name = "YourDailyLaughz", value = "yourdailylaughz"
},
Object {
name = "yourfavorite", value = "yourfavorite"
},
Object {
name = "Yoursie Thomas", value = "yoursie-thomas"
},
Object {
name = "You Suck at Photoshop", value = "you-suck-at-photoshop"
},
Object {
name = "Youth in Revolt", value = "youth-in-revolt"
},
Object {
name = "Youtube Next Lab", value = "youtube-next-lab"
},
Object {
name = "YSAP", value = "ysap"
},
Object {
name = "yt3d:aspect=16:9", value = "yt3daspect169"
},
Object {
name = "yt3d:enable=true", value = "yt3denabletrue"
},
Object {
name = "yt3d:metadata=user", value = "yt3dmetadatauser"
},
Object {
name = "yt3d:swap=true", value = "yt3dswaptrue"
},
Object {
name = "y tu mama tambien", value = "y-tu-mama-tambien"
},
Object {
name = "YuGiOh", value = "yugioh"
},
Object {
name = "Yugo Koral", value = "yugo-koral"
},
Object {
name = "Yuri Baranovsky", value = "yuri-baranovsky"
},
Object {
name = "Yvan Attal", value = "yvan-attal"
},
Object {
name = "Yvette Nicole Brown", value = "yvette-nicole-brown"
},
Object {
name = "yvonne de carlo", value = "yvonne-de-carlo"
}]
If I stringify it first before console.logging it:
JSON.stringify(source);
I get:
[{
"name": "Yahoo",
"value": "yahoo"
}, {
"name": "yahtzee",
"value": "yahtzee"
}, {
"name": "Yakov Smirnoff",
"value": "yakov-smirnoff"
}, {
"name": "Yarbrough",
"value": "yarbrough"
}, {
"name": "yard sales",
"value": "yard-sales"
}, {
"name": "yarmulke",
"value": "yarmulke"
}, {
"name": "yawning",
"value": "yawning"
}, {
"name": "Yeah Yeah Yeahs",
"value": "yeah-yeah-yeahs"
}, {
"name": "Yeardly Smith",
"value": "yeardly-smith"
}, {
"name": "YearOne",
"value": "yearone"
}, {
"name": "Yeasayer",
"value": "yeasayer"
}, {
"name": "yelle",
"value": "yelle"
}, {
"name": "yelling",
"value": "yelling"
}, {
"name": "yellowpages",
"value": "yellowpages"
}, {
"name": "yellowstone",
"value": "yellowstone"
}, {
"name": "yemen",
"value": "yemen"
}, {
"name": "Yeoman",
"value": "yeoman"
}, {
"name": "Yes Dear",
"value": "yes-dear"
}, {
"name": "Yes Men",
"value": "yes-men"
}, {
"name": "yeti",
"value": "yeti"
}, {
"name": "yiddish",
"value": "yiddish"
}, {
"name": "ymca",
"value": "ymca"
}, {
"name": "yodeling",
"value": "yodeling"
}, {
"name": "yoga",
"value": "yoga"
}, {
"name": "yogurt",
"value": "yogurt"
}, {
"name": "Yoko Ono",
"value": "yoko-ono"
}, {
"name": "Yo-Landi Vi$$er",
"value": "yo-landi-vier"
}, {
"name": "yo momma",
"value": "yo-momma"
}, {
"name": "YONKERS",
"value": "yonkers"
}, {
"name": "yosemite",
"value": "yosemite"
}, {
"name": "yoshimoto",
"value": "yoshimoto"
}, {
"name": "Yoshio Yoda",
"value": "yoshio-yoda"
}, {
"name": "you got served",
"value": "you-got-served"
}, {
"name": "YourDailyLaughz",
"value": "yourdailylaughz"
}, {
"name": "yourfavorite",
"value": "yourfavorite"
}, {
"name": "Yoursie Thomas",
"value": "yoursie-thomas"
}, {
"name": "You Suck at Photoshop",
"value": "you-suck-at-photoshop"
}, {
"name": "Youth in Revolt",
"value": "youth-in-revolt"
}, {
"name": "Youtube Next Lab",
"value": "youtube-next-lab"
}, {
"name": "YSAP",
"value": "ysap"
}, {
"name": "yt3d:aspect=16:9",
"value": "yt3daspect169"
}, {
"name": "yt3d:enable=true",
"value": "yt3denabletrue"
}, {
"name": "yt3d:metadata=user",
"value": "yt3dmetadatauser"
}, {
"name": "yt3d:swap=true",
"value": "yt3dswaptrue"
}, {
"name": "y tu mama tambien",
"value": "y-tu-mama-tambien"
}, {
"name": "YuGiOh",
"value": "yugioh"
}, {
"name": "Yugo Koral",
"value": "yugo-koral"
}, {
"name": "Yuri Baranovsky",
"value": "yuri-baranovsky"
}, {
"name": "Yvan Attal",
"value": "yvan-attal"
}, {
"name": "Yvette Nicole Brown",
"value": "yvette-nicole-brown"
}, {
"name": "yvonne de carlo",
"value": "yvonne-de-carlo"
}]
Is there any way I can convert source into an array that looks like:
["Yahoo", "yahtzee", "Yakov Smirnoff", etc...]
Basically I just need the "name"s and not the "value"s, and I need them all in one array. How can this be done?
As an alternative to the other answers, you could use Array.prototype.map. Note, though, that it's fairly new and not available in older browsers -- for these, I recommend es5-shim.
var names = source.map(function(item) { return item.name });
Update: With ES6, it would look something like this:
const names = source.map(item => item.name)
Just use a simple for loop:
var arr = [];
for (var i = 0; i < objects.length; i++) {
arr.push(objects[i].name);
}
Update 06 July 2020
In ES6, there are three (3) variations to convert an Object to an Array as follows:
const MyObjects = { key1: 'value 1', key2: 'value 2', };
// Method 1: Converts the keys to Array
// --------------------------------------
Object.keys(MyObjects);
// ['key1', 'key2']
// Method 2 Converts the Values to Array
// --------------------------------------
Object.values(MyObjects);
// ['value 1', 'value 2']
// Method 3 Converts both Values and Keys
// --------------------------------------
Object.entries(MyObjects);
// [ ['key1', 'value 1'], ['key2', 'value 2'] ]
Converting an Array back to an Object can be done as follows:
const array = [ ['one', 1], ['two', 2], ];
Object.fromEntries(array);
// { one: 1, two: 2 }
Your outer structure is an array containing a bunch of object literals. Push the name property of each object literal onto a new array, via a simple for loop.
var outArray = [];
for (i=0; i<inArray.length; i++ {
outArray.push(inArray[i].name);
}
console.log(outArray);
var result = [];
for (var i in source)
result.push(source[i].name);