I have a Json response which looks like this.
[
{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
]
I have another array called "a" which has only id [1,2,3,4,5]. Now i have to compare every element in the array with json response object id. For example, the first element of array "a" exists in json response object , then its respective name should be retrieved and stored in another new array called "b" -> [name1]. The second element of array "a" exists in json response object , then its respective name should be retrieved and appended in "b" array -> [name1,name2]. The third element of array "a" does not exists in json response object , hence no name. In this case, Instead of name, "0" should be appedned in b array for that id -> [name1,name2,0]. The fourth element of array "a" exists in json response object , then its respective name should be retrieved and appended in b array -> [name1,name2,0,name4]. The fifth element of array "a" exists in json response object , then its respective name should be retrieved and appended in b array -> [name1,name2,0,name4,name5].
I tried to implement this by the following code. But instead of [name1,name2,0,name4,name5] , I am getting [name1,name2,name4,name5,0]
for (var i = 0; i < a.length; i++) {
if (a.includes(jsonResponse[i].id)) {
b.push(jsonResponse[i].name);
}
else{
b.push("0");
}
}
You need to search for each element of b in the entire jsonResponse array, not just test the current index of jsonResponse.
Use .find() to find the element with the ID you're looking for.
let jsonResponse = [{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
];
let a = [1, 2, 3, 4, 5];
let b = a.map(id => {
let found = jsonResponse.find(u => u.id == id);
return found ? found.name : "0";
});
console.log(b);
You can use Map collection to have O(1) while accessing to the desired element when you map your elements:
let mapResponse = new Map(jsonResponse.map(s=> [+s.id, s.name]));
const result = a.map(id => mapResponse.get(id) || '0')
An example:
let jsonResponse = [
{
"name": "name1",
"id": "1"
},
{
"name": "name2",
"id": "2"
},
{
"name": "name4",
"id": "4"
},
{
"name": "name5",
"id": "5"
}
];
let a = [1, 2, 3, 4, 5];
let mapResponse = new Map(jsonResponse.map(s=> [+s.id, s.name]));
const result = a.map(id => mapResponse.get(id) || '0')
console.log(result);
Related
Let us say I have an object below and I have 2 variable. The length of the object is always fixed.
I wanted to assign the object index attribute value to variable A and object index 1 to variable B.
I can do like A = data[0].attributeValue; and B = data[1].attributeValue;
but is there a better and clean way to do this ? Thanks for any help or any idea. Appreciated.
#sample output
A = 'Test A'
B = 'Test B'
#sample variable
let A = '';
let B = '';
#sample object
data = [
{
"id": 13,
"type": "1",
"attributeValue": "Test A"
},
{
"id": 14,
"type": "2",
"attributeValue": "Test B"
}
]
You can read about Destructuring assignment but it won't help much .. well maybe a little:
data = [{
"id": 13,
"type": "1",
"attributeValue": "Test A"
},
{
"id": 14,
"type": "2",
"attributeValue": "Test B"
}
]
var [{attributeValue: A}, {attributeValue: B}] = data;
console.log(A, B)
I'm using knockoutjs, but the question is really in Javascript domain.
I have variable vm.filteredSerivces() which contains all services by all employees.
Now, I want to just preserve those filteredSerivces where is vm.filteredSerivces()[0].GroupedServices[x].EmployeeId == 3684 (x is the number of index number of each object in GroupedServices object list)
I tried as follows:
var filteredSrvcs = vm.filteredSerivces()[0].GroupedServices.filter(x => x.EmployeeId != Id).remove();
vm.filteredSerivces(filteredSrvcs );
But I changed structure in that way, and my bindings in html is not corresponding.
Is there any other way to just remove this sub-sub object, and to preserve a structure as it is?
Here is the
Here's an example that maps a new array of new objects and the filter is set to only include the GroupedServices items where Id == 2000
let res = data.map(({ServiceTypeName, GroupedServices}) =>{
GroupedServices= GroupedServices.filter(({Id}) => Id == 2000);
return {ServiceTypeName,GroupedServices }
})
console.log(res)
<script>
let data =
[
{
"ServiceTypeName": "Type 1",
"GroupedServices": [{
"Id": 1,
"Name": "A"
}, {
"Id": 2,
"Name": "A"
},
{
"Id": 28456,
"Name": "AGSADGJS"
}]
},
{
"ServiceTypeName": "Type 2",
"GroupedServices": [{
"Id": 1203,
"Name": "AHASJ"
}, {
"Id": 2000,
"Name": "AHSJD"
},
{
"Id": 284536,
"Name": "UEHNCK"
}]
}];
</script>
I have below array. First object is the original data. Inside array is the changed value. I am trying to create a final data by matching with the Name field with inside array. which should look like
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1111"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf"},
[
**{"Name":"hunt9988ggggggggggggdfsf1118","Id":"1"}, // Changed value
{"Name":"hunt9988ggggggggggggdfsf1118","Id":"2"}**
]
]
Final Data
var a =
[
{"Id":"1","Test":"Name1","Name":"hunt9988ggggggggggggdfsf1118"},
{"Id":"2","Test":"Name2","Name":"hunt9988ggggggggggggdfsf1118"}
]
I am trying with below code
var result = a.map(item => ({ value: item.Id, text: item.Name}));
console.log(result)
Like this?
Note I modify the original array
let a = [{
"Id": "1",
"Test": "Name1",
"Name": "hunt9988ggggggggggggdfsf1111"
},
{
"Id": "2",
"Test": "Name2",
"Name": "hunt9988ggggggggggggdfsf"
},
[{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "1"
}, // Changed value
{
"Name": "hunt9988ggggggggggggdfsf1118",
"Id": "2"
}
]
]
const replaceArray = a.find(item => Array.isArray(item))
replaceArray.forEach(item => a.find(aItem => aItem.Id === item.Id).Name=item.Name)
a = a.filter(item => item.Id)
console.log(a)
var items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
I have this array of objects named 'items'. I get itemselected = 3 from the database.
I need to convert this 3 into the following form.
0:Object
id:3
label:"Item3"
Similarly, if i have a value 2 coming from the database, i should convert it to
0:Object
id:2
label:"Item2"
Can anyone please let me hint of how to get it solved. i am not here to get the answer. These questions are quite tricky for me and i always fail to get the logic right. Any advice on how to master this conversions will be of great help. thanks.
Since you tagged underscore.js, this should be very easy:
var selectedObject = _.findWhere(items, {id: itemselected});
Using ECMA6, you can achieve the same using .find method on arrays:
let selectedObject = items.find(el => el.id === itemselected);
With ECMA5, you can use filter method of arrays. Be careful that filter returns undefined if no element has been found:
var selectedObject = items.filter(function(el) { return el.id === itemselected});
Use jquery $.map function as below
$.map(item, function( n, i ) { if(n["id"] == 3) return ( n );});
Based on the title of your question: «convert integer to array of object». You can use JavaScript Array#filter.
The filter() method creates a new array with all elements that
pass the test implemented by the provided function.
Something like this:
var items = [{
"id": 1,
"label": "Item1"
},
{
"id": 2,
"label": "Item2"
},
{
"id": 3,
"label": "Item3"
}
];
var value = 2;
var result = items.filter(function(x) {
return x.id === value;
});
console.log(result); // Prints an Array of object.
Try this
var obj = {} ;
items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
items.map(function(n) { obj[n.id] = n });
Here is the JQuery extend page.
What I would expect this to do is take two arrays, join them together and create uniform properties for each resulting array element. How do I get this to work as expected?
var a = [];
a.push({ "id": 1, "text": "one" });
a.push({ "id": 2, "text": "two" });
a.push({ "id": 3, "text": "three" });
var b = [];
b.push({"id":3 , "selected":true});
var c = [];
$.extend(c,a,b);
What I would expect is that the resulting array would include:
{ "id": 1, "text": "one", "selected": false }
{ "id": 2, "text": "two", "selected": false }
{ "id": 3, "text": "three", "selected": true }
but instead it seems to just copy the first array over top of the second:
{ "id": 3, "text": null, "selected": true }
{ "id": 2, "text": "two" }
{ "id": 3, "text": "three" }
The documentation includes:
When we supply two or more objects to $.extend(), properties from all of the objects are added to the target object.
What am I doing wrong, or how would I accomplish this otherwise?
EDIT: Jball's suggestion implemented:
var a = [];
a.push({ "id": 1, "text": "one" });
a.push({ "id": 2, "text": "two" });
a.push({ "id": 3, "text": "three" });
var b = [];
b.push({ "id": 3, "selected": true });
var c = [];
for (var index = 0; index < a.length; index++) {
var tempresult = {};
var tempb = b.filter(
function (ele, idx, collection) {
return (collection[idx].id == index + 1);
});
if (tempb.length == 0)
tempb = [{ "id": index + 1, "selected": false }];
$.extend(tempresult, a[index], tempb[0]);
c.push(tempresult);
}
produces:
[{"id":1, "selected":false, "text": "one"},
{"id":2, "selected":false, "text": "two"},
{"id":3, "selected":true, "text": "three"}]
That's the answer. Now I wonder if it can be cleaned up a bit.
I'm not sure if you noticed it, but the $.extend() function is intended for properties of objects, not elements of an array.
It seems like you need to create a function to loop through the arrays, and call $.extend() on matching elements to get your desired result. You would have to decide whether you want to add or ignore non-matching elements from the second array.
The problem is that jQuery has no idea what elements in your array are matching, and so matches them by index, though I'm not sure why the result for the first item has "text": "three" instead of "text": "one", unless it is attempting to match by the individual items properties after it does an $.extend() based on index.