How can I assign key value from array of object to another array object
I would like to assign the key:value pair to the existing array of object from the another array of objects.
I have check this thread but it is not working in my case.
I have tried something like this but that is not returning the desired output that I am looking for.
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
let result;
var A1 = DataA.options.map((v) => {
console.log(v);
result = v;
})
var A2 = DataB.options.map(v => {
result.options = v;
console.log("result",result);
})
let arr3 = DataA.options.map((item, i) => Object.assign({}, item, DataB[i]));
console.log(arr3);
Result will be I need as below:
const DataA = {
"id": 57,
"status": true,
"options": [{ "id": 1, "name": "Type A", "value": 10 },
{ "id": 2, "name": "Type B", "value": 20 },
{ "id": 3, "name": "Type C", "value": 30 }]
}
I need to merge the deep clone of the array that is slightly different from this thread.
The linked duplicate does actually address your question, but you need to adjust it to your situation and not just copy paste.
DataA.options = DataA.options.map((item, i) => Object.assign({}, item, DataB.options[i]));
but since this mutates the original DataA object anyway, you may as well just use forEach() and avoid creating the intermediate array from .map().
DataA.options.forEach((item, i) => Object.assign(item, DataB.options[i]));
Both of the above assume that the options arrays of both objects are a. of the same length, and b. sorted by id. To avoid these assumptions you can use .find() to look for matching elements instead of relying on index.
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
const DataA = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "name": "Type A" },
{ "id": 2, "name": "Type B" },
{ "id": 3, "name": "Type C" }]
}
const DataB = {
"id": 57,
"status": true,
"options": [
{ "id": 1, "value": 10 },
{ "id": 2, "value": 20 },
{ "id": 3, "value": 30 }]
}
DataA.options.forEach(item =>
Object.assign(item, DataB.options.find(({ id }) => id === item.id)));
console.log(DataA)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I have an array of objects like this one:
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
I want to replace the status.code by the one given in this other array of objects:
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
My idea is to map the first array and the use the find function (or filter) to loop the second array and when the ID's match change the values but I'm missing something, how can i do this the most optimized for performance and readability way?
let res: any[];
res = arr2.map((x: any) =>
arr1.find((y: any) =>
(y.data.id === x.id) ? 'logic if match' : 'return'
));
I would first change the format of arr2 in such a way that it is easier to access in such a format: (If you can easily change how you get this data, it would be better I think. Otherwise, transform the data as below.)
const idStatusCodeMap = {
"10": "green",
"20": "yellow"
}
We do this so we can just look if there is idStatusCodeMap[10] or idStatusCodeMap[anyId]. This makes it possible that you only loop through arr1, not a nested loop for both arr1 and arr2.
Then, loop through arr1 and replace the colours if necessary. If suppose, a new colour is not found on idStatusCodeMap, such as for id = 30, then don't do anything for that.
let arr1 = [{
"ref": 1,
"index": "300",
"data": {
"id": 10,
"status": {
"code": "red"
}
}
}, {
"ref": 2,
"index": "301",
"data": {
"id": 20,
"status": {
"code": "blue"
}
}
}];
let arr2 = [{
"id": 10,
"content": {
"name": "green"
}
}, {
"id": 20,
"content": {
"name": "yellow"
}
}];
let idStatusCodeMap = {}
//transpiling arr2 to more performant hashMap
arr2.forEach(item => {
idStatusCodeMap[item.id] = item.content.name;
})
console.log(idStatusCodeMap);
arr1 = arr1.map(item => {
//if the id of an item in arr1 is found in code map, replace it with new value.
//if not found, it will skip.
if(idStatusCodeMap[item.data.id]) {
item.data.status.code = idStatusCodeMap[item.data.id]
}
return item;
})
console.log(arr1);
I'm trying to filter some objects based on another array of objects. So I'm getting data from an API. These are for example receipts:
[
{
"id": 1,
"name": "test",
"category": {
"id": 1,
"name": "Cookies",
},
},
{
"id": 2,
"name": "test2",
"category": {
"id": 2,
"name": "Candy",
},
}
]
Then I'm trying to filter the objects on the category name based on another array of categories.
I've created a function for this:
function onSelectCategory(category) {
let receiptsList = receipts.filter((a) =>
a.category.includes(category.name)
);
setReceiptsView(receiptsList);
setSelectedCategory(category);
}
const category = [ { "id": 2, "name": "Candy" } ];
onSelectCategory(category);
When I run this function, I get an empty Array []. I can't really figure out what I'm doing wrong.
Since the param seems to be an array of objects, you need to use Array#some for comparison instead:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const receiptsList = receipts.filter(({ category }) =>
categories.some(({ name }) => name === category.name)
);
console.log(receiptsList);
Another solution using Set:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const categorySet = new Set(categories.map(({ name }) => name));
const receiptsList = receipts.filter(({ category }) =>
categorySet.has(category.name)
);
console.log(receiptsList);
Assuming that category (the parameter) is a string, the issue is that you are attempting to get the attribute name from the string, when you should be comparing the string to the object.
Try this:
a.category.name == category;
instead of
a.category.includes(category.name)
I may be wrong aboout assuming that category is a string, please clarify by telling us what the parameter category is equal to.
I have the following array
[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }
How can I convert that to
[ { "id": '1', "name": "Test" }, { "id": '2', "name": "Test2" }
For all the objects in an array, you want to convert a property type from number to string. You can use Array.forEach to achieve the same.
let arr = [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }];
arr.forEach(v => v.id += '');
console.log(arr);
I'm trying to filter an array of objects where the filter is another array (of integers) which are values of properties of the first array. I've managed to make it work but I'm not sure if it's the best way. Since I'm a beginner in javascript, I'd appreciate any suggestions/improvements.
The items.json file contains an object with an array of objects. I want to filter all the objects (within that array) that have an id equal to the "ids" on the itemsids array.
code:
const itemsall = require('./items.json');
let itemsids = [1, 403, 3];
let filtereditems = [];
itemsids.forEach(id => {
itemsall.items.forEach(item => {
if (id === item.id) {
filtereditems.push(item);
}
});
});
items.json (a small part of it)
{
"items": [
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
},
{
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
}
]
}
output: (expected)
[
{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
},
{
"id": 403,
"name": "Cool Incense",
"img": "http://www.serebii.net/pokemongo/items/incense.png"
},
{
"id": 3,
"name": "Ultraball",
"img": "http://www.serebii.net/pokemongo/items/ultraball.png"
}
]
Thanks!
You can use filter() and indexOf() to return filtered array.
var data = {
"items": [{
"id": 0,
"name": "Egg",
"img": "http://www.serebii.net/pokemongo/items/egg.png"
}, {
"id": 1,
"name": "Pokeball",
"img": "http://www.serebii.net/pokemongo/items/20pokeballs.png"
}, {
"id": 2,
"name": "Greatball",
"img": "http://www.serebii.net/pokemongo/items/greatball.png"
}]
}
let itemsids = [1, 403, 3];
var result = data.items.filter(function(e) {
return itemsids.indexOf(e.id) != -1
})
console.log(result)
With ES6/ES7 you can use includes() like this.
var result = data.items.filter((e) => itemsids.includes(e.id));
Am having an arrray of Objects which again contains the id's of the parent Object:
eg:-
$scope.result=[
{
"id": 1,
"name": ABC,
"type": PQR,
"parentId": 2
},
{
"id": 2,
"name": ABC,
"type": PQR,
"parentId": 1
}]
I would like to convert this JSON in to the following wherin I will be having the parentObject in place of parentId's
$scope.result=[
{
"id": 1,
"name": ABC,
"type": a,
"parentId": {
"id": 2,
"name": PQR,
"type": b,
"parentId": 1
}
},
{
"id": 2,
"name": PQR,
"type": b,
"parentId": {
"id": 1,
"name": ABC,
"type": a
}
}
]
Can anybody help me with this conversion..
Assuming parentId will reference to one element
angular.forEach($scope.result, function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});
Since your tags doesn't contain angularjs, I'm using Array.prototype.forEach here
$scope.result.forEach(function(result) {
var obj = $scope.result.filter(function(ele) {
return result.parentId === ele.id;
})[0];
result.parentId = obj;
});
Will do 2 loops first one to fill a hash with keys of the ids, second will loop to replace parent id with actual object:
$scope = {}
$scope.result=[
{
"id": 1,
"name": "ABC",
"type": "PQR",
"parentId": 2
},
{
"id": 2,
"name": "ABC",
"type": "PQR",
"parentId": 1
}]
parents = {}
for(i=0;i<$scope.result.length;i++){
parents[$scope.result[i]["id"]] = jQuery.extend({}, $scope.result[i]); // Clone object
}
for(i=0;i<$scope.result.length;i++){
$scope.result[i]["parentId"] = parents[$scope.result[i]["parentId"]]
}
$scope.result