I have a JSON file. I'm pulling data from this file with fetch. But I want to get the first element in all the elements of the array I pulled. I tried this but couldn't find it. Can you help me ?
MY JSON DATA :
{
"cols": [
"Name Surname",
"Company",
"Email",
"Date",
"Country",
"City"
],
"data": [
[
"Hyacinth Vincent",
"Duis Corporation",
"iaculis.enim#magnaCrasconvallis.ca",
"28/06/2022",
"Eritrea",
"Lyubertsy"
],
[
"Brenden Martinez",
"Volutpat Nunc Associates",
"iaculis#estMauris.org",
"24/03/2021",
"British Indian Ocean Territory",
"Colwood"
],
[
"Lunea Kinney",
"Ornare Facilisis Eget Incorporated",
"rutrum.eu#liberoMorbiaccumsan.ca",
"20/10/2021",
"Jordan",
"Yorkton"
],
[
"Rhona Mooney",
"Sed Et PC",
"placerat#sodalesat.ca",
"10/11/2020",
"Azerbaijan",
"Shrewsbury"
]
]
}
MY JS CODE :
fetch("api/tesodev.json")
.then((response) => response.json())
.then((data) => {
let cols = data.cols;
let responseData = data.data;
for (let index = 0; index < responseData.length; index++) {
let newResponseData = responseData.map(function (el, i) {
console.log(el[i]);
});
}
console.log(cols[0]);
});
Exactly what I'm trying to do is to get to the first elements of all the elements of the data array.
I want to access the data of "Hyacinth Vincent", "Brenden Martinez", "Lunea Kinney", "Rhona Mooney".
The only thing you're doing wrong is mapping over the whole child array and logging every part of it, when what you want is the first element:
const data = {
"cols": [
"Name Surname",
"Company",
"Email",
"Date",
"Country",
"City"
],
"data": [
[
"Hyacinth Vincent",
"Duis Corporation",
"iaculis.enim#magnaCrasconvallis.ca",
"28/06/2022",
"Eritrea",
"Lyubertsy"
],
[
"Brenden Martinez",
"Volutpat Nunc Associates",
"iaculis#estMauris.org",
"24/03/2021",
"British Indian Ocean Territory",
"Colwood"
],
[
"Lunea Kinney",
"Ornare Facilisis Eget Incorporated",
"rutrum.eu#liberoMorbiaccumsan.ca",
"20/10/2021",
"Jordan",
"Yorkton"
],
[
"Rhona Mooney",
"Sed Et PC",
"placerat#sodalesat.ca",
"10/11/2020",
"Azerbaijan",
"Shrewsbury"
]
]
}
let cols = data.cols;
let responseData = data.data;
for (let index = 0; index < responseData.length; index++) {
console.log(responseData[index][0])
}
(I would strongly suggest you change your data format; an array of objects would be much less fragile:
...
"data": [
{
name: "Hyacinth Vincent",
company: "Duis Corporation",
email: "iaculis.enim#magnaCrasconvallis.ca",
date: "28/06/2022",
country: "Eritrea",
city: "Lyubertsy"
},
{
...
ummm...
I think there are multiple problems in this
newResponseData will be array of item having values undefined as console.log() returns undefined.
I think this two lines can help.
Can you check at your end
let responseData = data.data;
const finaldata = responseData.map(item => item [0])
You need to access the current row in your for loop, then access the first element of this row.
fetch("api/tesodev.json")
.then((response) => response.json())
.then((data) => {
let cols = data.cols;
let responseData = data.data;
for (let index = 0; index < responseData.length; index++) {
const myDataRow = responseData[index];
const theFirstDataOfMyRow = myDataRow[0];
console.log(theFirstDataOfMyRow);
}
console.log(cols[0]);
});
You can use a double index to access the first field. [i][0] will access the first field in the ith object,
let responseData = <json>;
for (let index = 0; index < responseData.length; index++) {
console.log(responseData[i][0]);
}
You're almost doing it the way you want it work.
const data = {
"cols": [
"Name Surname",
"Company",
"Email",
"Date",
"Country",
"City"
],
"data": [
[
"Hyacinth Vincent",
"Duis Corporation",
"iaculis.enim#magnaCrasconvallis.ca",
"28/06/2022",
"Eritrea",
"Lyubertsy"
],
[
"Brenden Martinez",
"Volutpat Nunc Associates",
"iaculis#estMauris.org",
"24/03/2021",
"British Indian Ocean Territory",
"Colwood"
],
[
"Lunea Kinney",
"Ornare Facilisis Eget Incorporated",
"rutrum.eu#liberoMorbiaccumsan.ca",
"20/10/2021",
"Jordan",
"Yorkton"
],
[
"Rhona Mooney",
"Sed Et PC",
"placerat#sodalesat.ca",
"10/11/2020",
"Azerbaijan",
"Shrewsbury"
]
]
}
// Simplyfied, get data, use only data, only putput first entry in the array.
data.data.forEach((person) => {
console.log(person[0])
})
// Would be something like this:
/*
fetch("api/tesodev.json")
.then((response) => response.json())
.then((data) => {
let cols = data.cols
let persons = data.data
for (i = 0; i < persons.length; i++) {
console.log(persons[i][0])
}
})
*/
Related
I want to select every data with same key in json from selectbox. For example, I want to select all values with "author" key by putting them in the selectbox.
In the same way, I want to select the values corresponding to the "country" key by putting them in a selectbox.
My JSON
"kitap": [
{
"author": "Chinua Achebe",
"country": "Nigeria",
"imageLink": "images/things-fall-apart.jpg",
"language": "English",
"link": "https://en.wikipedia.org/wiki/Things_Fall_Apart\n",
"pages": 209,
"title": "Things Fall Apart",
"year": 1958
},
{
"author": "Hans Christian Andersen",
"country": "Denmark",
"imageLink": "images/fairy-tales.jpg",
"language": "Danish",
"link": "https://en.wikipedia.org/wiki/Fairy_Tales_Told_for_Children._First_Collection.\n",
"pages": 784,
"title": "Fairy tales",
"year": 1836
}
]
}
My javascript
let table2 = document.getElementById("tr2")
var books = fetch("kitap.json")
.then(res=> res.json())
.then(veri => {for(let data in veri ) {
for(deger of veri[data]) {
table2.innerHTML+= `
<td><select><option value="${deger.author}"></select></td>
<td><select><option value="${deger.country}"></select></td>
<td><select><option value="${deger.imageLink}"></select></td>
`
}
}})
how can i edit?
So this is one approach. The code is untested but should provide enough information for you to get started.
let table2 = document.getElementById("tr2");
let select1 = document.getElementById("ddlAuthor");
let select2 = document.getElementById("ddlCountry");
var books = fetch("kitap.json")
.then(res => res.json())
.then(veri => {
// Sets do not contain duplicates.
let setOfAuthors = new Set();
let setOfCountries = new Set();
for (let data in veri) {
for (deger of veri[data]) {
table2.innerHTML += `
<td><select><option value="${deger.author}"></select></td>
<td><select><option value="${deger.country}"></select></td>
<td><select><option value="${deger.imageLink}"></select></td>`
setOfAuthors.add(deger.author);
setOfCountries.add(deger.country);
}
// clear and fill <select> with <option>s.
PopulateDDL(select1, setOfAuthors);
PopulateDDL(select2, setOfCountries);
}
});
function populateDDL(ddl, setOfData) {
let distinctSortedArray = Array.from(setOfData).sort();
clearDDL(ddl);
for (var i = 0; i < distinctSortedArray.length; i++)
ddl.add(new Option(distinctSortedArray[i]));
}
function clearDDL(ddl) {
while (ddl.options.length) {
ddl.remove(0);
}
}
I have JSON with the following structure as an input:
{
"143334": ["VW", "Golf", "Diesel or Gas", "Affordable", "Blue, red or white"],
"344389": ["VW", "Passat", "Diesel or Gas", "More expensive"],
"484612": ["Audi", "A8", "Diesel", "Premium"],
"234234": ["Renault", "Megane", "not too much info"]
}
There is a unique id as key, and as value is an array of brand, model, and characteristics.
What is needed is to create a JavaScript function that when receives this input will return as output a sorted array of brands and models, models being another sorted array of model, unique id, and characteristics.
The output for the above input should be:
[
{
"brand": "Audi",
"models": [
{
"model": "A8",
"id": "484612",
"characteristics": ["Diesel", "Premium"]
}
]
},
{
"brand": "Renault",
"models": [
{
"model": "Megane",
"id": "234234",
"characteristics": ["not too much info"]
}
]
},
{
"brand": "VW",
"models": [
{
"model": "Golf",
"id": "143334",
"characteristics": ["Diesel or Gas", "Affordable", "Blue, red or white"]
},
{
"model": "Passat",
"id": "344389",
"characteristics": ["Diesel or Gas", "More expensive"]
}
]
}
]
Firstly, I've parsed the input, then tried to map through it as it would be an array in order to build the result. I have no idea how to sort it alphabetically by brand and by models:
function doMagic(input) {
const result = [];
const parsedInput = JSON.parse(input);
for (const brand in parsedInput) {
result.push({"brand": brand[0], "models": brand[1], "id": brand});
}
return result;
}
You first have to check, if the brand is already in the array, and (after it's created) push the new model into the array.
let json = '{"143334": ["VW", "Golf", "Diesel or Gas", "Affordable", "Blue, red or white"],"344389": ["VW", "Passat", "Diesel or Gas", "More expensive"],"484612": ["Audi", "A8", "Diesel", "Premium"],"234234": ["Renault", "Megane", "not too much info"]}';
function doMagic(json) {
let res = [];
let arr = JSON.parse(json)
Object.keys(arr).forEach(k => {
let tempIndex = res.findIndex(r => r.brand === arr[k][0])
if(-1 === tempIndex) { // if the brand isn't in the array yet
tempIndex = res.push({
brand:arr[k][0],
models:[]
})-1
}
res[tempIndex].models.push({
"model": arr[k][1],
"id": k,
"characteristics": arr[k].slice(2)
})
})
res.sort((a,b) => a.brand.localeCompare(b.brand))
res.forEach(e => e.models.sort((a,b) => a.model.localeCompare(b.model)))
return res
}
console.log(doMagic(json))
You can do this.
let jsonObj = '{"143334": ["VW", "Golf", "Diesel or Gas", "Affordable", "Blue, red or white"],"344389": ["VW", "Passat", "Diesel or Gas", "More expensive"],"484612": ["Audi", "A8", "Diesel", "Premium"],"234234": ["Renault", "Megane", "not too much info"]}';
function doMagic(input) {
const parsedInput = JSON.parse(input);
var ids = Object.keys(parsedInput);
var mappingObj = {};
for(let id of ids){
if(mappingObj[parsedInput[id][0]]){
mappingObj[parsedInput[id][0]].push({
model:parsedInput[id][1],
id:id,
characteristics:parsedInput[id].slice(2)
})
}else{
mappingObj[parsedInput[id][0]]= [
{
model:parsedInput[id][1],
id:id,
characteristics:parsedInput[id].slice(2)
}
]
}
}
var brands = Object.keys(mappingObj)
brands.sort(function(a,b){
if(a>b){return 1;}
else if(a<b){return -1;}
else {return 0;}
})
var finalObj = [];
for(var i=0;i<brands.length;i++){
mappingObj[brands[i]].sort(function(a,b){
if(a.model>b.model){return 1;}
else if(a.model<b.model){return -1;}
else {return 0;}
})
finalObj.push({
brand:brands[i],
models:mappingObj[brands[i]]
})
}
return finalObj;
}
console.log(doMagic(jsonObj))
I have 2 objects and I want to 'transplant' values from one object into the other.
The first object I am drawing data from looks like:
var userData = {
Data: [
{
Amount: 430140.68,
Year: "2015",
AccountName: "Account 1"
},
{
Amount: 458997.32,
Year: "2016",
Name: "Account 2"
},
]
}
The 2nd object I am placing data into looks like:
[
{
"name": "Account 1",
"data": [
0,
0
],
},
{
"name": "Account 2",
"data": [
0,
0
],
}
]
My goal is to take the Amount form the first object and place it in the data array of the 2nd. Each year corresponds to a value in the 'data` array.
So, the resulting updated object should look like:
[
{
"name": "Account 1",
"data": [
430140.68,
0
],
},
{
"name": "Account 2",
"data": [
0,
458997.32
],
}
]
To try to achieve this I have the following code:
const yearArrLength = yearsArr.length;
const generatedObj = new Array(yearArrLength).fill(0);
// Push name and populate data array with 0s.
for (var key of Object.keys(userData.Data)) {
var accName = userData.Data[key].AccountName;
if (!generatedObj.find(key => key.name === accName)){
generatedObj.push({'name': accName, 'data': blankDataArr});
}
}
for (var key of Object.keys(userData.Data)) {
var accName = userData.Data[key].AccountName;
var accAmount = userData.Data[key].Amount;
var accYear = userData.Data[key].Year;
// Get location of years array value
var yearArrIndex = yearsArr.indexOf(accYear);
for (var key of Object.keys(generatedObj)) {
if (generatedObj[key].name == accName) {
generatedObj[key].data[yearArrIndex] = accAmount;
}
}
}
However, this seems to populate all of the data array values, eg:
[
{
"name": "Account 1",
"data": [
430140.68,
458997.32
],
},
{
"name": "Account 2",
"data": [
430140.68,
458997.32
],
}
]
I'm completely stumped as to why. The if statement should be checking if there is a matching account name, but it doesn't seem to fire.
Would anyone know what I've done wrong?
It looks like you're pushing the exact same blankDataArr each time - you're not pushing a new array, you're pushing the same array to all.
For a more minimal example:
const subarr = [];
const arr = [subarr, subarr];
arr[0].push('x');
console.log(JSON.stringify(arr));
// both items in `arr` have changed
// because both refer to the exact same subarr object
For what you're trying to do, it looks like it'd be a lot easier to make an object or Map indexed by AccountName first, that way you just have to access or create the AccountName property while iterating, and assign to the appropriate year.
const yearsArr = ['2015', '2016'];
const userData = {
Data: [
{
Amount: 430140.68,
Year: "2015",
AccountName: "Account 1"
},
{
Amount: 458997.32,
Year: "2016",
AccountName: "Account 2"
},
]
};
const dataByAccountName = new Map();
for (const { AccountName, Amount, Year } of userData.Data) {
if (!dataByAccountName.has(AccountName)) {
// Create an entirely new array:
dataByAccountName.set(AccountName, yearsArr.map(() => 0));
}
const index = yearsArr.indexOf(Year);
dataByAccountName.get(AccountName)[index] = Amount;
}
const result = [...dataByAccountName.entries()].map(([name, data]) => ({ name, data }));
console.log(result);
Currently, I have my JSON and a function that loops through the results and then through the URLs. I am trying to only get the first type value which is detail. I have tried looking for ways to get the first value and found that using [0] can work in some situations but not this one. Am I indexing incorrectly? and is there a more succinct way of coding this nested for loop?
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}
]
}]
}
};
function test(data) {
const dataArr = data.data['results'];
for (let i = 0; i < dataArr.length; i++) {
console.log(dataArr[i].urls);
const urlArr = dataArr[i].urls
for (let j = 0; j < urlArr.length; j++) {
console.log(urlArr[j].type[0]);
}
}
}
test(data);
A functional approach...
Your question seems a little vague, but I think you're looking for the value of type from the first item in each urls array.
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}]
}]
}
};
const types = data.data.results.map(({ urls: [first, ...rest] }) => first.type);
console.log(types);
Let's break this down...
data.data.results.map(...)
Array.prototype.map will return a new array with the results of calling the provided function on every element in the results array.
({ urls: ... })
This is called destructuring. It defines a new variable, urls, that is assigned the value of the urls property as we iterate through the results items.
({ urls: [first, ...rest] })
The value of the urls variable we defined will be an array. We only care about the first item in the array, so we'll spread the array, defining a new variable called first that's assigned the value of the first item, and a variable, rest, that will be an array of the rest of the items. Basically, take the head of the array. These operations are called spread and rest, respectively.
({ urls: [first, ...rest] }) => first.type
Finally, return the value of the type property from the first urls item.
If I'm completely wrong
And you want the "details" item within each urls array, then a slight change will suffice:
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}]
}]
}
};
const urls = data.data.results.map(({ urls }) =>
urls.find(({ type }) => type === 'detail')
);
console.log(urls);
If you'd like to learn more about functional programming, Eric Elliott wrote an excellent set of articles on functional programming in JavaScript. Here's the first one.
If the format of your data is fixed you can use.
You can also try different approaches of safe reading data from object.
You can use utilities like these:
data.data['results'][0].urls[0]
If you are not sure about the 0th index you can use find:
data.data['results'][0].urls.find(url => url.type === 'detail')
Try this-
function test(data)
{
var dataArr = data.data.results;
for (let i = 0; i < dataArr.length; i++) {
const urlArr = dataArr[i].urls
for (let j = 0; j < urlArr.length; j++) {
console.log(urlArr[0].type);
}
}
}
You can use find to find the exact element by type prop.
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}
]
}]
}
};
function test(data) {
const dataArr = data.data['results'];
for (let i = 0; i < dataArr.length; i++) {
//console.log(dataArr[i].urls);
const urlArr = dataArr[i].urls
const detail = urlArr.find(url => url.type == 'detail');
console.log(detail.url);
}
}
test(data);
Something like this?
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}
]
}]
}
};
const result = [].concat.apply([], data.data.results.map(x => x.urls.map(y => y.type)))[0];
console.log(result);
const data = {
"data": {
"results": [{
"name": "Deadpool",
"urls": [{
"type": "detail",
"url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "wiki",
"url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
},
{
"type": "comiclink",
"url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
}
]
}]
}
};
console.log(data.data.results.map(el => el.urls).flat().find(el => el.type === 'detail'));
My target is if the id from digital_assets and products matches then get the value of URL fro digital_assets and ProductName from products object. I'm able to traverse through the object and get the values of digital_assets and products but need some help to compare these two objects based on IDs to get the value of URL and ProductName. Below is what I've done so far.
var data = [{
"digital_assets": [{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}]
}, {
"products": [{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},{
"id": ["BB002", "AA002"],
"ProductName": "PROD 555"
}]
}
];
$.each(data, function () {
var data = this;
//console.log(data);
$.each(data.digital_assets, function () {
var dAssets = this,
id = dAssets['id'];
// console.log(id);
});
$.each(data.products, function () {
var proData = this,
prod_id = proData['id'];
// console.log(prod_id);
$.each(prod_id, function () {
var arr_id = this;
console.log(arr_id);
});
});
});
Do I need to create new arrays and push the values into the new arrays? Then concat() these array to one. ? Bit lost any help will be appreciated.
Here is one way you can do this via Array.reduce, Array.includes, Object.entries and Array.forEach:
var data = [{ "digital_assets": [{ "id": "AA001", "url": "https://via.placeholder.com/150" }, { "id": "AA002", "url": "https://via.placeholder.com/150" } ] }, { "products": [{ "id": ["BB001", "AA001"], "ProductName": "PROD 485" }, { "id": ["BB002", "AA002"], "ProductName": "PROD 555" } ] } ]
const result = data.reduce((r,c) => {
Object.entries(c).forEach(([k,v]) =>
k == 'digital_assets'
? v.forEach(({id, url}) => r[id] = ({ id, url }))
: v.forEach(x => Object.keys(r).forEach(k => x.id.includes(k)
? r[k].ProductName = x.ProductName
: null))
)
return r
}, {})
console.log(Object.values(result))
You can use Array.prototype.find, Array.prototype.includes and Array.prototype.map to achieve this very gracefully.
let data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
];
// Find the 'digital_assets' array
let assets = data.find(d => d['digital_assets'])['digital_assets'];
// Find the 'products' array
let products = data.find(d => d['products'])['products'];
// Return an array of composed asset objects
let details = assets.map(a => {
return {
id : a.id,
url : a.url
name : products.find(p => p.id.includes(a.id)).ProductName
};
});
console.log(details);
changed answer to fit your needs:
var data = [
{
"digital_assets": [
{
"id": "AA001",
"url": "https://via.placeholder.com/150"
},
{
"id": "AA002",
"url": "https://via.placeholder.com/150"
}
]
},
{
"products": [
{
"id": ["BB001", "AA001"],
"ProductName": "PROD 485"
},
{
"id": ["BB002","AA002"],
"ProductName": "PROD 555"
}
]
}
]
let matchingIds = [];
let data_assetsObject = data.find(element => {
return Object.keys(element).includes("digital_assets")
})
let productsObject = data.find(element => {
return Object.keys(element).includes("products")
})
data_assetsObject["digital_assets"].forEach(da => {
productsObject["products"].forEach(product => {
if (product.id.includes(da.id)){
matchingIds.push({
url: da.url,
productName: product.ProductName
})
}
})
})
console.log(matchingIds);
working fiddle: https://jsfiddle.net/z2ak1fvs/3/
Hope that helped. If you dont want to use a new array, you could also store the respective data within the element you are looping through.
Edit:
I think i know why i got downvoted. My example works by making data an object, not an array. changed the snippet to show this more clearly.
Why is data an array anyway? Is there any reason for this or can you just transform it to an object?
Edit nr2:
changed the code to meet the expectations, as i understood them according to your comments. it now uses your data structure and no matter whats in data, you can now search for the objects containing the digital_assets / products property.
cheers
https://jsfiddle.net/2b1zutvx/
using map.
var myobj = data[0].digital_assets.map(function(x) {
return {
id: x.id,
url: x.url,
ProductName: data[1].products.filter(f => f.id.indexOf(x.id) > -1).map(m => m.ProductName)
};
});