This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I'm new to Javascript, ES6 , and i have hit the wall with this problem
This is the JSON that i'm getting from a webservice
{
"products": [
{
"id": 2,
"id_default_image": "21",
"price": "35.900000",
"name": [
{
"id": "1",
"value": "item 1"
},
{
"id": "2",
"value": "item 1 alternate name"
}
]
},
{
"id": 4,
"id_default_image": "4",
"price": "29.000000",
"name": [
{
"id": "1",
"value": "item 2"
},
{
"id": "2",
"value": "item 2 alternate name"
}
]
}
]
}
The name property in the above JSON is an array and i need only the value of the first element. The desired output would be like below
{
"products": [
{
"id": 2,
"id_default_image": "21",
"price": "35.900000",
"name": "item 1"
},
{
"id": 4,
"id_default_image": "4",
"price": "29.000000",
"name": "item 2"
}
]
}
I'm working on a react-native project. What would be the easiest way to achieve this? Any help would be greatly appreciated. Thanks.
Similar to Ele's answer but if you don't want to change the original object. You can use map to iterate over the product objects and return a new products array:
const data = {"products":[{"id":2,"id_default_image":"21","price":"35.900000","name":[{"id":"1","value":"item 1"},{"id":"2","value":"item 1 alternate name"}]},{"id":4,"id_default_image":"4","price":"29.000000","name":[{"id":"1","value":"item 2"},{"id":"2","value":"item 2 alternate name"}]}]};
const products = data.products.map(obj => ({ ...obj, name: obj.name[0].value }));
console.log(products);
Also used: spread syntax
Well, you can use the function forEach or a simple for-loop and assign the first value to the attribute name.
let obj = { "products": [ { "id": 2, "id_default_image": "21", "price": "35.900000", "name": [ { "id": "1", "value": "item 1" }, { "id": "2", "value": "item 1 alternate name" } ] }, { "id": 4, "id_default_image": "4", "price": "29.000000", "name": [ { "id": "1", "value": "item 2" }, { "id": "2", "value": "item 2 alternate name" } ] } ]}
obj.products.forEach(o => (o.name = o.name[0].value));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this
const productsArray = products.map((product, index) => {
const obj = {};
obj["id"] = product["id"];
obj["id_default_image"] = product["id_default_image"];
obj["price"] = product["price"],
obj["name"] = product.name[0].value;
return obj;
});
const obj = {};
obj.products = productsArray;
console.log(obj);//will print you the desired output you want
Related
I need inner join with two array in javascript like this:
array1 =
[
{
"id": 1,
"name": "Tufan"
},
{
"id": 2,
"name": "Batuhan"
},
{
"id": 3,
"name": "Hasan"
}
]
array2 =
[
{
"name": "yyy",
"externalid": "1",
"value": "Asd"
},
{
"name": "aaaa"
"externalid": "2",
"value": "ttt"
}
]
expectedArray =
[
{
"id": 1,
"name": "Tufan",
"externalid": "1",
"value": "Asd"
},
{
"id": 2,
"name": "Batuhan",
"externalid": "2",
"value": "ttt"
}
]
rules:
on: array2.externalid = array1.id
select: array1.id, array1.name, array2.externalid, array2.value
My approach:
array1.filter(e => array2.some(f => f.externalid == e.id));
// I need help for continue
How can I make this?
Doesn't matter information: I use ES5 and pure javascript
You can do it like this:
const res = array2.map((item) => {
const related = array1.find((el) => el.id == item.externalid);
return { ...item, ...related };
});
Using a map to loop over the array2 and a find to get the array1 relative.
Hey guys I have the following array that's used to display a flatlist within my app.
Array [
Object {
"data": "Item 1",
"id": "1",
"subjects": "1,8,9,23,11,15,16,14,20",
},
Object {
"data": "Item 2",
"id": "2",
"subjects": "8,11,2,4,16,19",
},
Object {
"data": "Item 3",
"id": "3",
"subjects": "16,20,14,11,9,2",
},
Object {
"data": "Item 4",
"id": "4",
"subjects": "1,16,19",
},
]
However I would like to sort this array based off the subjects value. In the app the user can select a couple of subjects which are represented by numbers so lets say the users selected subjects are:
11, 4, 2, 1
I would like to sort the array so that the items with 3 or more subjects in common with the user are sorted to the top and then items with two and then 1 and then none so the array above should look like this after sorting:
Array [
Object {
"data": "Item 2",
"id": "2",
"subjects": "8,11,2,4,16,19",
},
Object {
"data": "Item 1",
"id": "1",
"subjects": "1,8,9,23,11,15,16,14,20",
},
Object {
"data": "Item 3",
"id": "3",
"subjects": "16,20,14,11,9,2",
},
Object {
"data": "Item 4",
"id": "4",
"subjects": "0,16,19",
},
]
How can I achieve this?
I have been searching around the array sort function:
Array.prototype.sort()
However I have only seen how to sort based off number comparisons I have never seen an array sorted based off values in common. Please could someone help me with this!
EDIT
Array [
Object {
"data": "Item 2",
"id": "2",
"subjects": "8,11,2,4,16,19",
"ranking": "green",
},
Object {
"data": "Item 1",
"id": "1",
"subjects": "1,8,9,23,11,15,16,14,20",
"ranking": "amber",
},
Object {
"data": "Item 3",
"id": "3",
"subjects": "16,20,14,11,9,2",
"ranking": "amber",
},
Object {
"data": "Item 4",
"id": "4",
"subjects": "0,16,19",
"ranking": "red",
},
]
You could create an object with counts of selected subjects and sort descending by this value.
const
data = [{ data: "Item 1", id: "1", subjects: "1,8,9,23,11,15,16,14,20" }, { data: "Item 2", id: "2", subjects: "8,11,2,4,16,19" }, { data: "Item 3", id: "3", subjects: "16,20,14,11,9,2" }, { data: "Item 4", id: "4", subjects: "1,16,19" }],
selected = [11, 4, 2, 1],
counts = data.reduce((r, { id, subjects }) => {
r[id] = subjects
.split(',')
.reduce((s, v) => s + selected.includes(+v), 0);
return r;
}, {});
data.sort((a, b) => counts[b.id] - counts[a.id]);
console.log(data);
console.log(counts);
.as-console-wrapper { max-height: 100% !important; top: 0; }
This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Remove duplicates form an array
(17 answers)
Closed 1 year ago.
I'm trying to build a method in javascript which can filter from an array of object one only value and have a result that value only once without having duplicates
sharing a snippet and more details what I want to achieve
const arr = [{
"id": "1",
"value": "something"
}, {
"id": "1",
"value": "something"
}, {
"id": "2",
"value": "something"
}, {
"id": "2",
"value": "something"
},
{
"id": "3",
"value": "something"
},
{
"id": "3",
"value": "something"
},
{
"id": "3",
"value": "something"
}];
const result = arr.filter(res => res.id).map(ele => ele.id);
console.log(result);
As you see result is an array like this
["1", "1", "2", "2", "3", "3", "3"]
What I would like to get is as follow
["1", "2", "3"]
The idea is to extract only one ID per result.
You can use a Set as follows:
const arr = [
{ "id": "1", "value": "something" },
{ "id": "1", "value": "something" },
{ "id": "2", "value": "something" },
{ "id": "2", "value": "something" },
{ "id": "3", "value": "something" },
{ "id": "3", "value": "something" },
{ "id": "3", "value": "something" }
];
const result = [...arr.reduce((set,{id}) => {
set.add(id);
return set;
}, new Set)];
console.log(result);
I have the following data that is an array of nested objects:
"categories": [
{
"id": 1,
"name": "Category 1",
"years": [
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" }
]
},
{
"id": 2,
"name": "Category 2",
"years": [
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" }
]
}
]
I want to extract unique years in a separate array (desired output):
[
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" },
]
When I map out the years, I'm getting an array of arrays, how should I extract the unique objects for years?
let years = categories.map( (c) => { return c.years })
You can use a Map to filter duplicate years from the array of values using id as the key, and reduce() on both categories and years using the map as the accumulator:
const categories = [{
"id": 1,
"name": "Category 1",
"years": [
{ "id": 1, "name": "1" },
{ "id": 2, "name": "2" }
]
},
{
"id": 2,
"name": "Category 2",
"years": [
{ "id": 2, "name": "2" },
{ "id": 3, "name": "3" }
]
}
];
const years = categories.reduce(
(map, category) => category.years.reduce(
(map, year) => map.set(year.id, year),
map
),
new Map()
);
console.log([...years.values()]);
You can use reduce and Map
let data = [{"id": 1,"name": "Category 1","years": [{ "id": 1, "name": "1" },{ "id": 2, "name": "2" }]},{"id": 2,"name": "Category 2","years": [{ "id": 2, "name": "2" },{ "id": 3, "name": "3" }]}]
let final = data.reduce((op,{years}) => {
years.forEach(({id, name}) => {
let key = id + '-' + name
op.set(key, op.get(key) || {id, name})
})
return op
},new Map())
console.log([...final.values()])
This question already has answers here:
Remove duplicates in an object array Javascript
(10 answers)
Closed 5 years ago.
I have an array containing arrays of objects which I need to compare.
I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays of objects (most are comparing two arrays of objects or just comparing the objects within a single array)
This is the data (below is a JSFiddle with code sample)
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
I want to remove all duplicate arrays of objects, regardless of the length of data (there could be a lot more records).
I managed to get the unique ones extracted into an object:
const unique = data.reduce(function(result, obj) {
return Object.assign(result, obj)
}, [])
That doesn't work for me though, because I need 1 of the duplicated arrays to remain and the returned data to be an array as well, instead of an object. E.g.:
// result I need
[
[
{
"id":"65",
"name":"Some object name",
"value":90
},
{
"id":"89",
"name":"Second Item",
"value":20
}
],
[
{
"id":"14",
"name":"Third one",
"value":10
}
]
]
So how do I compare each array of objects to the others in the parent array and preserve one of each duplicated or unique array of objects?
JSFiddle
you can achieve so by using function.As below. Not sure about best optimum way of doing so.
var testArray = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
]
function removeDuplicatesFromArray(arr){
var obj={};
var uniqueArr=[];
for(var i=0;i<arr.length;i++){
if(!obj.hasOwnProperty(arr[i])){
obj[arr[i]] = arr[i];
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);
const data = [
[
{
"id": "65",
"name": "Some object name",
"value": 90
},
{
"id": "89",
"name": "Second Item",
"value": 20
}
],
[
{
"id": "89",
"name": "Second Item",
"value": 20
},
{
"id": "65",
"name": "Some object name",
"value": 90
}
],
[
{
"id": "14",
"name": "Third one",
"value": 10
}
]
];
const temp = {};
const result = [];
data.forEach(itemArr => {
const items = itemArr.filter(item => {
const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
temp[`${item.id}-${item.name}-${item.value}`] = true;
return isUnique;
});
if (items.length !== 0)
result.push(items);
});
console.log(result);