Combining JavaScript Arrays - javascript

I would like to take a JavaScript object that is formatted like:
results = {
names: [
"id",
"first_name"
],
values: [
[
1234,
"Fred"
],
[
4321,
"Joe"
],
[
1123,
"Mary"
]
]
}
and turn into this:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
I tried doing something like this, but I can't get the structure correct:
var data = []
for (i=0; i < results['values'].length; i++ ){
var innerData = []
for (b=0; b < results['names'].length; b++ ){
innerData.push([name:results['names'][b], value: results['values'][i][b]])
}
data.push(innerData)
}
console.log(data)

Problem 1:
results = {
[id: 1234, name: "Fred"],
[id: 4321, name: "Joe"],
[id: 1123, name: "Mary"]
}
and
var data = []
and
[name:results['names'][b]…
An array [] consists a set of values in order.
An object {} consists of a set of key:value pairs.
You are using the wrong one each time. Use {} where you have [] and vice versa
Problem 2:
You say you want objects with id and name keys, but you are trying to create name and value keys. Use the property names you actually want.

Try this:
var data = [];
for (i in results['values']){
var innerData = {}
var value = results['values'][i];
for (b in value){
var key = results['names'][b];
innerData[key] = value[b];
}
data.push(innerData);
}
console.log(data);

Related

How can I include an array into my JSON object in Javascript?

I'm trying to prepare an array into a json object to send to an API.
I'm struggling to figure out how to manipulate my array into the right shape.
My array looks something like this.
data: [
["Lisa", "Heinz", "1993-04-15" ],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
]
I'd like it to be a json object looking like this:
{person:[{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},{"name":"","last_name":"","dob":""}],"object_id":259,"test":"bob","attribute":"bob123"}
Currently I do this:
let json = {}
for (let person of formData) {
const identifier = `person${formData.indexOf(person)}`;
json[identifier] = {
name: person[0],
last_name: person[1],
dob: person[2]
}
}
json.object_id = "259";
json.wp_test = "bob";
json.attribute = "bob123";
Which outputs something like this:
{"person0":{"name":"Lisa","last_name":"Heinz","dob":"1993-04-15"},"person1":{"name":"Bob","last_name":"Dylan","dob":"1998-09-12"},"person2":{"name":"Cabbage","last_name":"Man","dob":"1990-01-11"},"person3":{"name":"","last_name":"","dob":""},"object_id":259,"wp_test":"bob","attribute":"bob123"}
I've tried a variety of things to get the right shape - what's an easily understandable way to get there?
It's just a matter of matching the correct keys/indexes.
var data = [
["Lisa", "Heinz", "1993-04-15"],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
]
var persons = data.reduce(function(agg, item) {
agg.push({
name: item[0],
last_name: item[1],
dob: item[2],
})
return agg;
}, [])
var final = {
person: persons,
object_id: 259,
wp_test: 'bob',
attribute: 'bob123',
}
console.log(final)
.as-console-wrapper {max-height: 100% !important}
You can simply achieve this by iterating the input array with the help of Array.map() method.
Live Demo :
const data = [
["Lisa", "Heinz", "1993-04-15" ],
["Bob", "Dylan", "1998-09-12"],
["Cabbage", "Man", "1990-01-11"],
["", "", ""]
];
const jsonObj = {};
jsonObj.person = data.map(arr => ({ name: arr[0], last_name: arr[1], dob: arr[2] }));
jsonObj.object_id = "259";
jsonObj.wp_test = "bob";
jsonObj.attribute = "bob123";
console.log(jsonObj);

how to convert json map to array ? Angular

I have the json like follow example, i would like to convert this json map to array for to be able to loop on it.
I use the Object.keys method but I don't know how to have a key => value format for the whole json.
I need to get the keys to make a table I know there is the pipe keyvalue but it's not what I need. or maybe I use it wrong
example json
{
"pays": "UK"
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
components.ts
get() {
this.myService.getUrl().subscribe(data => {
this.myArray = Object.keys(data).map((key) => {
return {
id: key,
name: data[key]
}
}):
}
Please try this
var input: any = {
"pays": "UK",
"test": [
[
"123456", // here i want key id
"blabla", // here i want key name
"lorem ipsum" // here i want key type
],
[
"654321",
"ipsum",
"blabla"
]
]
}
input .test = input.test.map((item: any) => {
return {
id: item[0],
name : item[1],
type : item[2]
}
})
This is one possible solution to transform array of strings into array of JSONs:
let input = {
pays: "UK",
test: [
[
"123456",
"blabla",
"lorem ipsum"
],
[
"654321",
"ipsum",
"blabla"
]
]
};
let result = {};
result.pays = input.pays;
result.test = [];
for (let i = 0; i < input.test.length; i++){
let testEl = input.test[i];
let resultObj = {};
resultObj.id = testEl[0];
resultObj.name = testEl[1];
resultObj.type = testEl[2];
result.test.push(resultObj);
}
console.log(result)

React - Filter JSON array if key exists [duplicate]

I have an array of objects and I'm wondering the best way to search it. Given the below example how can I search for name = "Joe" and age < 30? Is there anything jQuery can help with or do I have to brute force this search myself?
var names = new Array();
var object = { name : "Joe", age:20, email: "joe#hotmail.com"};
names.push(object);
object = { name : "Mike", age:50, email: "mike#hotmail.com"};
names.push(object);
object = { name : "Joe", age:45, email: "mike#hotmail.com"};
names.push(object);
A modern solution with Array.prototype.filter():
const found_names = names.filter(v => v.name === "Joe" && v.age < 30);
Or if you still use jQuery, you may use jQuery.grep():
var found_names = $.grep(names, function(v) {
return v.name === "Joe" && v.age < 30;
});
You can do this very easily with the [].filter method:
var filterednames = names.filter(function(obj) {
return (obj.name === "Joe") && (obj.age < 30);
});
You can learn more about it on this MDN page.
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [
{ name : "Joe", age:20, email: "joe#hotmail.com"},
{ name : "Mike", age:50, email: "mike#hotmail.com"},
{ name : "Joe", age:45, email: "mike#hotmail.com"}
];
var filteredNames = $(names).filter(function( idx ) {
return names[idx].name === "Joe" && names[idx].age < 30;
});
$(filteredNames).each(function(){
$('#output').append(this.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"/>
var nameList = [
{name:'x', age:20, email:'x#email.com'},
{name:'y', age:60, email:'y#email.com'},
{name:'Joe', age:22, email:'joe#email.com'},
{name:'Abc', age:40, email:'abc#email.com'}
];
var filteredValue = nameList.filter(function (item) {
return item.name == "Joe" && item.age < 30;
});
//To See Output Result as Array
console.log(JSON.stringify(filteredValue));
You can simply use javascript :)
For those who want to filter from an array of objects using any key:
function filterItems(items, searchVal) {
return items.filter((item) => Object.values(item).includes(searchVal));
}
let data = [
{ "name": "apple", "type": "fruit", "id": 123234 },
{ "name": "cat", "type": "animal", "id": 98989 },
{ "name": "something", "type": "other", "id": 656565 }]
console.log("Filtered by name: ", filterItems(data, "apple"));
console.log("Filtered by type: ", filterItems(data, "animal"));
console.log("Filtered by id: ", filterItems(data, 656565));
filter from an array of the JSON objects:**
var names = [{
name: "Joe",
age: 20,
email: "joe#hotmail.com"
},
{
name: "Mike",
age: 50,
email: "mike#hotmail.com"
},
{
name: "Joe",
age: 45,
email: "mike#hotmail.com"
}
];
const res = _.filter(names, (name) => {
return name.name == "Joe" && name.age < 30;
});
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
So quick question. What if you have two arrays of objects and you would like to 'align' these object arrays so that you can make sure each array's objects are in the order as the other array's? What if you don't know what keys and values any of the objects inside of the arrays contains... Much less what order they're even in?
So you need a 'WildCard Expression' for your [].filter, [].map, etc. How do you get a wild card expression?
var jux = (function(){
'use strict';
function wildExp(obj){
var keysCrude = Object.keys(obj),
keysA = ('a["' + keysCrude.join('"], a["') + '"]').split(', '),
keysB = ('b["' + keysCrude.join('"], b["') + '"]').split(', '),
keys = [].concat(keysA, keysB)
.sort(function(a, b){ return a.substring(1, a.length) > b.substring(1, b.length); });
var exp = keys.join('').split(']b').join('] > b').split(']a').join('] || a');
return exp;
}
return {
sort: wildExp
};
})();
var sortKeys = {
k: 'v',
key: 'val',
n: 'p',
name: 'param'
};
var objArray = [
{
k: 'z',
key: 'g',
n: 'a',
name: 'b'
},
{
k: 'y',
key: 'h',
n: 'b',
name: 't'
},
{
k: 'x',
key: 'o',
n: 'a',
name: 'c'
}
];
var exp = jux.sort(sortKeys);
console.log('#juxSort Expression:', exp);
console.log('#juxSort:', objArray.sort(function(a, b){
return eval(exp);
}));
You can also use this function over an iteration for each object to create a better collective expression for all of the keys in each of your objects, and then filter your array that way.
This is a small snippet from the API Juxtapose which I have almost complete, which does this, object equality with exemptions, object unities, and array condensation. If these are things you need or want for your project please comment and I'll make the lib accessible sooner than later.
Hope this helps! Happy coding :)
The most straightforward and readable approach will be the usage of native javascript filter method.
Native javaScript filter takes a declarative approach in filtering array elements. Since it is a method defined on Array.prototype, it iterates on a provided array and invokes a callback on it. This callback, which acts as our filtering function, takes three parameters:
element — the current item in the array being iterated over
index — the index or location of the current element in the array that is being iterated over
array — the original array that the filter method was applied on
Let’s use this filter method in an example. Note that the filter can be applied on any sort of array. In this example, we are going to filter an array of objects based on an object property.
An example of filtering an array of objects based on object properties could look something like this:
// Please do not hate me for bashing on pizza and burgers.
// and FYI, I totally made up the healthMetric param :)
let foods = [
{ type: "pizza", healthMetric: 25 },
{ type: "burger", healthMetric: 10 },
{ type: "salad", healthMetric: 60 },
{ type: "apple", healthMetric: 82 }
];
let isHealthy = food => food.healthMetric >= 50;
const result = foods.filter(isHealthy);
console.log(result.map(food => food.type));
// Result: ['salad', 'apple']
To learn more about filtering arrays in functions and yo build your own filtering, check out this article:
https://medium.com/better-programming/build-your-own-filter-e88ba0dcbfae

How to compare array values with object properties in this example?

This is my array:
const ids = [
"id1",
"id2",
"id3"
]
Object that is extracted via cookies
const data = [
{
id: "id3" // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
How can I compare first array values - ids with data.id, and if true, show some logic (for example - console.log(true)? I need it in if statement.
Please note that data.id. can be anything, from id1 to id3. I need to find a way to dynamically compare these values. In "real world" it id anything from 1 do 50000, but this is just a mock-up for the example.
Also I would appreciate Lodash example.
You can iterate all the elements in Array which are objects and using Object.keys, iterate all the keys in that object which could be compared with initial array of values.
const ids = [
"id1",
"id2",
"id3"
];
const data = [{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}];
const foundElems = [];
data.forEach((el) => {
Object.keys(el).forEach(elem => {
if (ids.indexOf(el[elem]) > -1) {
var Obj = {};
Obj[elem] = el[elem];
foundElems.push(Obj);
}
});
});
console.log(foundElems);
For each item in data, you check if the id is in the array of ids, and if yes, do something
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
// if we have the id in ids array, do something
if (data.some(d => ids.indexOf(d.id) > -1)) {
// do something
}
Using lodash:
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
// if we have the id in ids array, do something
if (_.some(data, d => ids.indexOf(d.id) > -1)) {
// do something
}
I think this is what you are looking for:
if (ids.indexOf(data.id) !== -1){
console.log('true')
}
Just run the next code:
<html>
<body>
<button onclick="compareIds()">Click me</button>
<script>
const ids = [
"id1",
"id2",
"id3"
]
const data = [
{
id: "id3", // dynamically populated and can vary, we need this property
prop2: "prop2", // not needed
prop3: "prop3" // not needed
}
]
function compareIds(){
var dataObject = findDataInObject();
for(var i = 0; i < ids.length; i++){
if (ids[i] == dataObject){
console.log("true");
}
else{
if(i == ids.length -1){
console.log("false");
}
}
}
}
function findDataInObject(){
for(key in data) {
if(data.hasOwnProperty(key)) {
var ArrayOfData = data[key];
var IdOfData = ArrayOfData.id;
return IdOfData;
}
}
}
</script>
</body>

javascript array of object with key

I've been searching and searching and haven't found a solution...even though, likely, it's simple. How do I create something that will give me this:
myArray['key1'].FirstName = "First1";
myArray['key1'].LastName = "Last1";
myArray['key2'].FirstName = "First2";
myArray['key2'].LastName = "Last2";
myArray['key3'].FirstName = "First3";
myArray['key3'].LastName = "Last3";
And then say something like, alert(myArray['key2'].FirstName);
And will I be able to iterate through it like:
for(i=0; i < myArray.length; i++){
//do whatever
}
Thanks in advance!
You can init an object something like that:
{
"key1": {FirstName: "first1", LastName: "last1"}
"key2": {FirstName: "first2", LastName: "last2"}
"key3": {FirstName: "first3", LastName: "last3"}
}
Sample function for init your array:
function initArray(){
for(var i=1; i< count+1; i++) {
var newElement = {}
newElement.FirstName = "first" + i;
newElement.LastName = "last" + i;
var keyName = "key" + i
var obj = {};
myArray[keyName] = newElement
}
}
Now "myArray["key2"] is accessible.
http://jsfiddle.net/jq5Cf/18/
You can't do what you're trying to do in javascript! (because javascript can't do associative arrays)
I would go for an object which has an internal array to store other things
var container = {};
container.things = [];
container.things.push({FirstName: 'First1', LastName: 'Last1'});
now you can do..
for(var i in container.things) {
alert(container.things[i].FirstName);
}
In JavaScript we use arrays like this, [] for Arrays and Objects are in {}
var MyArray = [
{FirstName: "Firsname1" , LastName: "Lasname1"},
{FirstName: "Firsname2" , LastName: "Lasname2"}
]
Your myarray variable construction is in notation of objects of objects.
var myArray = {'key1':
{
'FirstName' : "First1",
'LastName' : "Last1"
}};
In order to access the values should be like array of objects.
var myArray = [
{
'FirstName' : "First1",
'LastName' : "Last1"
},
];
or notation can be like below:
var data = {
code: 42,
items: [{
id: 1,
name: 'foo'
}, {
id: 2,
name: 'bar'
}]
};

Categories

Resources