I would like to rearrange an array of objects in javascript, which looks like this:
[{ year: "1950-12-20", product: ["product 1", "product 2, "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }]
so that I get two arrays, one with the products and one with the years when they appear.
a = ["product 1", "product 2", "product 3", "product 4"]
b = ["1950-12-20", [ "1950-12-20, "1951-12-20"],["1950-12-20", "1951-12-20", "1952-12-20"],"1952-12-20"]
I have tried to loop through each object through nestled for-loops, but how do I treat the array of strings in the object array in a nice way?
I don't know what kind of loop you have tested, but this type of code is not so long for what has to be done :
var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];
var nbData = data.length, iData;
var years = [], products = [], dictProductsYear = {};
var nbProducts, iProduct, p;
// Loop through years
for(iData = 0; iData < nbData; iData ++) {
products = data[iData].product;
nbProducts = products.length;
// Add the current year to the concerned products
for(iProduct = 0; iProduct < nbProducts; iProduct ++) {
p = products[iProduct];
// Registered product
if(dictProductsYear[p]) dictProductsYear[p].push(data[iData].year);
// Unregistered one
else dictProductsYear[p] = [ data[iData].year ];
}
}
var yearList = [], productList = [];
// Flatten the dictionary in 2 lists
for(p in dictProductsYear) {
productList.push(p);
yearList.push(dictProductsYear[p]);
}
This looks a bit like #Samuel Caillerie's code, but is more concise:
var data = [{ year: "1950-12-20", product: ["product 1", "product 2", "product 3"] }, { year: "1951-12-20", product: ["product 3", "product 2"] }, { year: "1952-12-20", product: ["product 3", "product 4"] }];
var yearsByProd = {};
for (var i=0; i<data.length; i++) {
var prod = data[i].product;
for (var j=0; j<prod.length; j++) {
if (prod[j] in yearsByProd)
yearsByProd[prod[j]].push(data[i].year);
else
yearsByProd[prod[j]] = [data[i].year];
}
}
var a, b;
b = (a = Object.keys(yearsByProd).sort()).map(function(prod) {
// add an if-else-statement here if you want to extract single years from their array
return yearsByProd[prod];
});
Related
I need some help with my code here. It's a jquery-bracket project.
I have an object that has an array inside, there's a line of array i want to loop so I don't have to manually generated those lines
var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var teams = "";
for (i = 0; i < team.length; i++) {
teams += [`["${team[i++]}"`, ` "${team[i]}"], \n`]
}
var singleElimination = {
"teams": [
// line that I needed for loop
[team[0], team[1]],
[team[2], team[3]],
],
"results": [
[
[
// also line that I needed for loop
[result[0], result[1]]
]
]
]
}
I have tried to pass the loop into a variable and passing them inside of an array, but it doesn't seems work.
sorry for my bad English, looking forward for the answer!
demo : https://quizzical-stonebraker-2d808a.netlify.com/
You can simply use team.join(',');
eg:-
var singleElimination = {
"teams": [
[team.join(',')]
var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var obj = {}
for(var i=0; i<team.length; i++){
obj[team[i]] = result[i];
}
console.log(obj)
var team = ["Team 1", "Team 2", "Team 3", "Team 4"];
var result = [1, 2, 2, 1];
var singleElimination = {
teams: [
// line that I needed for loop
[team[0], team[1]],
[team[2], team[3]]
],
results: [
[
[
// also line that I needed for loop
[result[0], result[1]],
[result[2], result[3]]
]
]
]
};
console.log("singleElimination", singleElimination);
var _teams = "";
singleElimination.teams.forEach(element => {
element.forEach((team, index) => {
_teams += element[index] + ", ";
});
});
var _teamResults = "";
singleElimination.results.forEach(element => {
element.forEach((team, index) => {
_teamResults += element[index] + ", ";
});
});
console.log("_teams", _teams);
console.log("_teamResults", _teamResults);
I have a array different objects
{
prac:[{
"name":"xxx",
"id":"1"
}],
abc: [{
"description":"this is test description",
"status":"active"
}]
}
Here I want to convert prac array to object.
You should take the first element of the array. That's it
var obj = {
prac: [{
"name": "xxx",
"id": "1"
}],
abc: [{
"description": "this is test description",
"status": "active"
}]
};
obj.prac = obj.prac[0];
console.log(obj);
Try this :
var jsonObj = {
prac:[{
"name":"xxx",
"id":"1"
}],
abc: [{
"description":"this is test description",
"status":"active"
}]
};
var arrObj = jsonObj.prac;
function toObject(arr) {
var newJson = {};
for (var i = 0; i < arr.length; ++i)
newJson[i] = arr[i];
return newJson;
}
console.log(toObject(arrObj));
I have 2 separate arrays which I need to merge into a third one so I can get all the data required.
Basically the 1st array has an id, and name and in order to get the address I need to search inside the 2nd array and match the id's so I can have all the data from the person.
Here is the data and code:
//Array 1
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"},{"id":"456","name":"name 2"}]}];
//Array 2
var myPersonArray = [{"person":[{"id":"123","address":"address 1"},{"id":"456","address":"address 2"}]}];
var arrayLength = myPeopleArray[0].people.length;
for (var i = 0; i < arrayLength; i++) {
console.log("id: " + myPeopleArray[0].people[i].id);
}
//Wanted Result:
[{"people":[
{
"id":"123",
"name":"name 1",
"address":"address 1"
},
{
"id":"456",
"name":"name 2",
"address":"address 2"
}
]
}]
How can I do this?
var myPeopleArray = [{"people":[{"id":"123","name":"name 1"}, {"id":"456","name":"name 2"}]}];
var myPersonArray = [{"person":[{"id":"123","address":"address 1"}, {"id":"456","address":"address 2"}]}];
for(var i=0;i<myPeopleArray[0].people.length;i++)
{
myPeopleArray[0].people[i].address = myPersonArray[0].person[i].address;
}
document.write(JSON.stringify(myPeopleArray));
You could iterate both arrays and build new object with the joined properties.
var myPeopleArray = [{ "people": [{ "id": "123", "name": "name 1" }, { "id": "456", "name": "name 2" }] }],
myPersonArray = [{ "person": [{ "id": "123", "address": "address 1" }, { "id": "456", "address": "address 2" }] }],
hash = Object.create(null),
joined = [],
joinById = function (o) {
if (!(o.id in hash)) {
hash[o.id] = {};
joined.push(hash[o.id]);
}
Object.keys(o).forEach(function (k) {
hash[o.id][k] = o[k];
});
};
myPeopleArray[0].people.forEach(joinById);
myPersonArray[0].person.forEach(joinById);
console.log(joined);
I have a json object as below in my web application. It's an array of product objects and each product object has a category property which contains an array of categories that the product belongs to.
var products = [
{
"id":1,
"name":"Product 1",
"price":10,
"category":[
{
"id":10,
"name":"Category 1"
},
{
"id":20,
"name":"Category 2"
}
]
},
{
"id":2,
"name":"Product 2",
"price":20,
"category":[
{
"id":20,
"name":"Category 2"
},
{
"id":30,
"name":"Category 3"
}
]
}
]
So now I want to display them grouped by categories so the end result will look like below. I am already using Underscore.js in my project so it will be good if I can use it to achieve this.
var categories = [
{
"id":10,
"name":"Category 1",
"products":[
{
"id":1,
"name":"Product 1",
"price":10
}
]
},
{
"id":20,
"name":"Category 2",
"products":[
{
"id":1,
"name":"Product 1",
"price":10
},
{
"id":2,
"name":"Product 2",
"price":20,
}
]
},
{
"id":30,
"name":"Category 3",
"products":[
{
"id":2,
"name":"Product 2",
"price":20,
}
]
}
]
I'm not entirely sure whether there is an out-of-the-box solution to this problem with underscore, however solving this by hand shouldn't be too hard, either:
var categoriesIndexed = {};
var categories = [];
products.forEach(function(product) {
product.category.forEach(function(category) {
// create a new category if it does not exist yet
if(!categoriesIndexed[category.id]) {
categoriesIndexed[category.id] = {
id: category.id,
name: category.name,
products: []
};
categories.push(categoriesIndexed[category.id]);
}
// add the product to the category
categoriesIndexed[category.id].products.push({
id: product.id,
name: product.name,
price: product.price
});
});
});
here is what I would do
var categories = [];
var cat = new Map();
var addUniqueCategory(category) { /* determine if category is already in list of categories, if not add it to categories */ };
products.each (function (item) {
item.categories.each(function (c) {
if (!cat.has(c.name)) cat.set(c.name, []);
var list = cat.get(c.name);
list.push( { id: item.id, name: item.name, price: item.price });
addUniqueCategory(c);
});
});
categories.each( function (c) {
var list = cat.get(c.name);
if (!c.products) c.products = [];
c.products.splice( c.length, 0, list);
});
roughly, I'm on a phone
How would I split the following AJAX response into three separate objects based on the attribute 'product_range' using JS/jQuery, i.e. one object array for all 'range-1' products, one for 'range-2' and so on?
[
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
]
I would just use reduce and push items into an object that holds arrays.
var items = [
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
];
var grouped = items.reduce( function (obj, item) {
if (!obj[item.product_range]) obj[item.product_range] = [];
obj[item.product_range].push(item);
return obj;
}, {});
console.log(grouped);
console.log(grouped["range-1"]);
Use the method "filterByProductRange" to filter out the data by product_range.
var obj = [
{
title: "Product 1",
price: "12.00",
product_range: "range-1"
},
{
title: "Product 2",
price: "12.00",
product_range: "range-2"
},
{
title: "Product 3",
price: "12.00",
product_range: "range-3"
}
];
function filterByProductRange(data, product_range) {
return data.filter(function(item) { return item['product_range'] == product_range; });
}
var range1= filterByProductRange(obj, 'range-1');
console.log(range1);
if you mean grouping your data by product_range, then:
//json is your json data
var result = {};
for(var i=0; i<json.length;i++)
{
if(result[json[i].product_range] === undefined) result[json[i].product_range] = [];
result[json[i].product_range].push(json[i]);
}
Something like this should group by range.
var ranged = {};
var data = [{
title: "Product 1",
price: "12.00",
product_range: "range-1"
}, {
title: "Product 2",
price: "12.00",
product_range: "range-2"
}, {
title: "Product 3",
price: "12.00",
product_range: "range-3"
}]
$.each(data, function(i, x) {
if (ranged[x.product_range]) {
ranged[x.product_range].push(x);
} else {
ranged[x.product_range] = [x];
}
});
console.log(JSON.stringify(ranged));
You should then be able to retrieve all object for a given range by querying the ranged object.
You can use $.map() to achieve a similar result.
var range1 = new Object(),
range2 = new Object(),
range3 = new Object();
$.map(data, function(d){
if (d.product_range === "range-1") {
for (var i in d) {
range1[i] = d[i];
}
}
});
Where data is your object array.
Here's a simple fiddle to demonstrate this.