Convert a two dimensional array into an array of objects - javascript

I have a two dimensional array, datas, that I want to convert to an array of objects.
The keys are in datas[0], I want to extract them, name, child, and size. and then append each attribute to it to get a master object. For some reason it overrides and is only showing one object when I try this?
var test = new Object();
for (i = 0; i < datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
test.update(obj);
}
I would like the final result to be:
[
{"name": "Billy", "parent":"Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
The datas array looks like:
[["Name", "Parent", "Size"], ["Billy", "Ann", "1"], ["Ben", "John", "1"] ... ]

You can't make an object without properties, so your desired result can't be achieved.
Assuming you want:
[
{"name": "Billy", "parent": "Ann", "size": "1"},
{"name": "Ben", "parent": "John", "size": "1"},
etc...
]
Try:
var test = [];
for(i = 0; i < datas.length; i++){
test.push({
name: datas[i][0],
parent: datas[i][1],
size: datas[i][2]
});
}
// do something with test

{
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
}
is not correct json. curly braces mean - object, object must be presented in key:value form. There are two possible correct json of this kind:
array of objects
[
{"name": "Billy", "parent":"Ann", "size"="1"},
{"name": "Ben", "parent": "John", "size" = "1"}
]
deep structure
{
"Billy" {"parent":"Ann", "size"="1"},
"Ben" {"parent": "John", "size" = "1"}
}
to generate first variant
var res = []
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.name = datas[i][0];
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.push(obj);
}
JSON.stringify(res);
to generate second variant
var res = new Object();
for(i = 0; i<datas.length; i++){
var obj = new Object();
obj.parent = datas[i][1];
obj.size = datas[i][2];
res.[datas[i][0]] = obj;
}
JSON.stringify(res);

Related

Filter object array based on string array "with partial match"

I have an array of objects and want to filter it based on values of another string array and remove the objects that doesn't contain any of the strings.
I tried using split for the string array and search for each term in a forEach but it didn't work then tried the following which works as a filter but it filters for exact match not partial.
var employees = [
{"name": "zxc asd", "age":"30"},
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"},
{"name": "zxc", "age":"28"},
];
var keepNames = ["asd", "qwe"];
keepNames = keepNames.map(name => {
return name.toLowerCase();
});
var filteredEmployees = employees.filter(emp => {
return keepNames.indexOf(emp.name.toLowerCase()) !== -1;
});
console.log( filteredEmployees );
Expected Output[
{"name": "zxc asd", "age":"30"},
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"}];
Actual Output [
{"name": "asd", "age":"24"},
{"name": "qwe", "age":"44"}]
I'd really appreciate any help.
Thanks in advance
You need to iterate the array with names keep as well and check the value.
var employees = [{ name: "zxc asd", age: "30" }, { name: "asd", age: "24" }, { name: "qwe", age: "44" }, { name: "zxc", age: "28" }],
keep = ["asd", "qwe"],
filtered = employees.filter(({ name }) =>
keep.some(n => name.toLowerCase().includes(n))
);
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
indexOf uses strict equality so it won't match partially.
You can use some and includes
var employees = [ {"name": "zxc asd", "age":"30"},{"name": "asd", "age":"24"},{"name": "qwe", "age":"44"},{"name": "zxc", "age":"28"},];
var filterBy = ["asd", "qwe"];
var filteredEmployees = employees.filter(emp => {
return filterBy.some(v => emp.name.toLowerCase().includes(v.toLowerCase()))
});
console.log(filteredEmployees);

javascript count number values repeated in a jsonArray items

i need to count the number of occurrences of values in jsonArray items in javascript.
consider this as my jsonArray:
{"name":"jack","age":23},
{"name":"john","age":20},
{"name":"alison","age":23},
{"name":"steve","age":25},
.
.
.
now for example i need to know how many times each age is repeated in this array, i want to count each value for each property, i mean i need a result like this :
name : {"jack" : 2,"james" : 10,"john" : 1,....}
age : {"23":10,"20":15,"25":2,....}
what is the simplest way to achieve this?
EDIT :
my array is very big and i don't want to call count function for each value. i want a code to count each value repeat times.
you can have a look at Array.prototype.reduce
function mapToProp(data, prop) {
return data
.reduce((res, item) => Object
.assign(res, {
[item[prop]]: 1 + (res[item[prop]] || 0)
}), Object.create(null))
;
}
const data = [
{"name": "jack", "age": 23},
{"name": "john", "age": 20},
{"name": "alison", "age": 23},
{"name": "steve", "age": 25}
];
console.log('mapAndCountByAge', mapToProp(data, 'age'))
You could use an object, where the keys and the values are used as property for the count.
var array = [{ name: "jack", age:23 }, { 'name': "john", age: 20 }, { name: "alison", age: 23 }, { name: "steve", age: 25 }],
result = {};
array.forEach(function (o) {
Object.keys(o).forEach(function (k) {
result[k] = result[k] || {};
result[k][o[k]] = (result[k][o[k]] || 0) + 1;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Not as elegant as Nina's and Hitmands' answers, but this is easier to understand for beginners (in case any beginner is reading this).
var jsonArray = [
{"name": "John", "age": 20},
{"name": "John", "age": 21},
{"name": "Doe", "age": 21},
{"name": "Doe", "age": 23},
{"name": "Doe", "age": 20},
];
var names = [],
ages = [];
// separate name data and age data into respective array
// only need to access the original data once
jsonArray.forEach(function(val){
names.push(val['name']);
ages.push(val['age']);
});
function aggregate(array){
var obj = {};
array.forEach(function(val){
if (!obj[val])
// create new property if property is not found
obj[val] = 1;
else
// increment matched property by 1
obj[val]++;
});
return JSON.stringify(obj);
}
console.log("Names: " + aggregate(names));
console.log("Ages: " + aggregate(ages));
In my opinion, Nina has the best answer here.
EDIT
In fact, when presented with large dataset (as OP stated that "the array is very big"), this method is about 45% faster than Nina's answer and about 81% faster than Hitmand's answer according to jsben.ch. I don't know why though.

Pivot or Transforming JavaScript object

I have the following JavaScript object. I need to generate a new object from the given object. What is the approach I should take in JavaScript?
[
{"name": "Dan", "city" : "Columbus", "ZIP":"47201"},
{"name": "Jen", "city" : "Columbus", "ZIP":"47201"},
{"name": "Mark", "city" : "Tampa", "ZIP":"33602"},
]
How can I transform or pivot to generate the following object?
[
{ "47201": [
{"name": "Dan", "city": "Columbus"},
{"name": "Jen", "city": "Columbus"},
],
"count": "2"
},
{ "33602": [
{"name": "Mark", "city": "Tampa"}
],
"count": "1"
}
]
I don't know why you want the .count property, when that can be accessed via the array's .length property, but anyway:
const input = [
{"name": "Dan", "city" : "Columbus", "ZIP":"47201"},
{"name": "Jen", "city" : "Columbus", "ZIP":"47201"},
{"name": "Mark", "city" : "Tampa", "ZIP":"33602"},
]
const working = input.reduce((acc, {ZIP, name, city}) => {
(acc[ZIP] || (acc[ZIP] = [])).push({name, city})
return acc
}, {})
const output = Object.keys(working)
.map(k => ({[k]: working[k], count: working[k].length}))
console.log(output)
Further reading:
Array .reduce()
Array .map()
Object.keys()
Unpacking fields from objects passed as function parameters
Computed property names
The below code will work for your requirement. The final result is stored in the variable result which holds the array object.
var source = [{
"name": "Dan",
"city": "Columbus",
"ZIP": "47201"
},
{
"name": "Mark",
"city": "Tampa",
"ZIP": "33602"
},
{
"name": "Jen",
"city": "Columbus",
"ZIP": "47201"
}
];
var result = [];
finalarr('ZIP');
function finalarr(propname) {
var obj = JSON.parse(JSON.stringify(source));
obj.forEach(function(elm,i) {
var arr = {};var chli=[];var charr={};
var flag = 0;
for (var prop in elm) {
if(prop != propname){
charr[prop]=elm[prop];
}
}
for(var i=0;i<result.length;i++){
if(result[i][elm[propname]]){
result[0][elm[propname]].push(charr);
//console.log(result[i][propname]);
flag = 1;
}
}
if(flag == 0){
chli.push(charr);
arr["count"] = checkarr(obj,propname,elm[propname]);
arr[elm[propname]]=chli;
result.push(arr);
}
});
}
function checkarr(obj,propname,value){
var count = 0;
obj.forEach(function(elm,i) {
if(elm[propname] == value){
count++;
}
});
return count;
}
console.log(result);

JavaScript: How to Get the Values from a Multi-Dimensional Array?

I'm trying to get the values from a multi-dimensional array. This is what I have so far.
I need the value of 99 and the image when I select the first option in the array, e.g. "Billy Joel".
var concertArray = [
["Billy Joel", "99", "equal.png"],
["Bryan Adams", "89", "higher.png"],
["Brian Adams", "25", "lower.png"]
];
function populate(){
for(i = 0; i < concertArray.length; i++){
var select = document.getElementById("test");
select.options[select.options.length] = new Option(concertArray[i][0], concertArray[i][1]);
}
}
You can try to transform the multi-dimensional array to an array of objects like this:
var concertArray = [
{name: "Billy Joel", value: 99, image: "equal.png"},
{name: "Bryan Adams", value: 89, image: "higher.png"},
{name: "Brian Adams", value: 25, image: "lower.png"}
];
Then you can access the items in the array like regular objects:
var concertName = concertArray[0].name;
var concertPrice = parseFloat(concertArray[0].value);
var concertImage = concertArray[0].image;
let concertArray = [
["Billy Joel", "99", "equal.png"],
["Bryan Adams", "89", "higher.png"],
["Brian Adams", "25", "lower.png"]
];
let i = 0;
console.log(concertArray[i][1]) // 99
console.log(concertArray[i][2]) // equal.png
AFAIK, the Option constructor only takes two arguments, the text and the value. If you want to pass more data, I suggest you use the HTML5 data API:
var opt = new Option(concertArray[i][0], concertArray[i][1]);
opt.setAttribute('data-image', concertArray[i][2]);
select.options[select.options.length] = opt;
Then you can grab it using getAttribute('data-image')
You can access values by using 2 for loops as below.
var concertArray = [
["Billy Joel", "99", "equal.png"],
["Bryan Adams", "89", "higher.png"],
["Brian Adams", "25", "lower.png"]
];
function populate(){
for(i=0;i<arr.length;i++)
{
for(j=0;j<arr[i].length;j++)
{
console.log(arr[i][j]);
}
}
}

Extracting data from JsonArray using JS/jQuery

I have a JsonArray something like this.
var json_array = [{ "text": "id", "size": 4}, { "text": "manifesto", "size": 4}, { "text": "also", "size": 4}, { "text": "leasing", "size": 4}, { "text": "23", "size": 4}];
Is there anyway to get me all the "text" property of this json_array in another array using Javascript/jQuery?
like:
var t_array = ["id","manifesto","also"....]
You can use $.map() to project the relevant information from your existing array into a new one:
var t_array = $.map(json_array, function(item) {
return item.text;
});
var t_array = [];
for (var i=0; i< json_array.length; i++)
t_array.push(json_array[i].text);
I think you'll need to build t_array by looping through json_array
something like:
var t_array = [];
$.each(json_array,function(i,o) {
t_array.push(o.text);
})
http://jsfiddle.net/bouillard/2c66t/

Categories

Resources