I have an array such as var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"]; and I would like to be able to loop through the array to create an object from each element.
var zoo = {
Dog : {
color: brown,
age: 4
},
Cat : {
color: black,
age: 12
I have found some solutions for defining the other properties with .keys and .values but I am stuck on how to name the object. Thanks for any help!
You can achieve the solution using Array.reduce.
reduce provides an elegant way to return desired output based on your array.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo=arr.reduce((zooObj, animal)=>
{
zooObj[animal] = {
color: 'black', //You can add color based on some logic here
age: 4 //You can add age based on some logic here
}
return zooObj
}, {})
console.log(zoo) //*Output*: { "Dog": { "color": "black", "age": 4 }, "Cat": { "color": "black", "age": 4 }, "Horse": { "color": "black", "age": 4 }, "Pig": { "color": "black", "age": 4 }, "Cow": { "color": "black", "age": 4 } }
You can try with below:
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["Red", "Blue", "Green", "Dark", "Yellow"];
var zoo={};
var i = 10;
var colorIndex = 0;
arr.forEach(v=>{
zoo[v]={};
zoo[v].age=i++;
zoo[v].color=colors[colorIndex++];
});
console.log(zoo);
You can simply do it in this way :
var objArr = {};
arr.forEach((data, index) => {
objArr[data] = data; //here you can add what ever value you want to add to that key
})
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo = {};
for (var i of arr ){
zoo[i] = {};
zoo[i].age = 'age'; //fill the age
zoo[i].color= 'your favorite color'; //fill with your favorite color
}
console.log(zoo);
This will do-
var animal = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var color=["red","green","blue","orange","yellow"];
var age=[2,5,8,6,23];
var obj={};
animal.forEach((e)=>{
obj[e]={};
obj[e].age=age[animal.indexOf(e)];
obj[e].color=color[animal.indexOf(e)];
})
console.log(obj)
You can do this by using below logic.
Here define color and age array and inside loop store this dynamically.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["brown","blak","white","red","gray"];
var ages = ["4","12","5","10","15"];
arr2 = {}
for(var i=0;i<arr.length;i++){
arr2[arr[i]] = {};
arr2[arr[i]].color = colors[i]; //fill the age
arr2[arr[i]].age= ages[i];
}
console.log(arr2);
https://jsfiddle.net/brahmpragya/w76xjm5y/29/
Related
I want to return the object containing the closest strings inside array inside an object, inside another array,
my indexOf() only return the exact string as true.
I tried replacing indexOf() with march(), matches(), includes() nothing works.
Please advice
let SellerList = [
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] },
{ supplyList: ["lamp", "dog", "cat", "man"] }
];
let stringToMatch = "app";
let filteredList = SellerList.filter(
(txt) => txt.supplyList.indexOf(stringToMatch) !== -1
);
the output i wish for is all the objects containing the closest strings for example:
[
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] }
];
You have an array inside an object, inside another array, so you want to target that inner array and call filter on it:
let SellerList = [{
supplyList: ['apple', 'orange', 'red apple']
}];
let stringToMatch = 'app';
let filteredList = SellerList[0].supplyList.filter(txt => txt.indexOf(stringToMatch) !== -1);
console.log(filteredList)
Please try the following solution
let SellerList = [
{ supplyList: ["apple", "orange", "red apple"] },
{ supplyList: ["apple juice", "drink", "green apple", "dream app"] },
{ supplyList: ["lamp", "dog", "cat", "man"] },
];
let stringToMatch = "app";
let filteredList = SellerList.reduce((previousValue, currentValue) => {
if (currentValue.supplyList.join().includes(stringToMatch)) {
previousValue = [...previousValue, { supplyList: currentValue.supplyList }];
}
return previousValue;
}, []);
console.log(filteredList);
See
Array.prototype.reduce()
Array.prototype.join()
You should try to match the inner strings of the supplyLists instead of the arrays themselves.
let SellerList = [
{ supplyList: ['apple','orange','red apple'] },
{ supplyList: ['apple juice','drink','green apple'] }
];
let stringToMatch = 'app';
let filteredList = SellerList.map(list => {
return list.supplyList.filter(item => {
return item.indexOf(stringToMatch) >= 0
})
});
console.log(filteredList);
This question already has answers here:
Comparing two arrays of objects, and exclude the elements who match values into new array in JS
(6 answers)
Closed 5 years ago.
I want to find unique elements in a which do not exist in b on the basis of name property
EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];
var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];
var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];
var data = [];
b.map((n)=>{
for(i=0;i<a.length;i++) {
if(n.name!= a[i].name){
data.push(a[i]);
}
}
})
console.log(data);
Use Array#filter to filter the a array and pass a predicate which uses Array#some to try to find an item. When there is no match, get those items
const a =[
{"name":"sam","color":"red" },
{"name":"rash","color":"blue" },
{"name":"rashffffish","color":"blue" }
];
const b = [
{"name":"sam","color":"red" },
{"name":"rash","color":"red" }
];
const filtered = a.filter(itemA => !b.some(itemB => itemA.name === itemB.name));
console.log(filtered);
From your code...
var a = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "blue"
}, {
"name": "rashffffish",
"color": "blue"
}];
var b = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "red"
}];
var data = a;
b.forEach((n) => {
for (i = 0; i < data.length; i++) {
if (n.name === a[i].name) {
var ind= data.indexOf(a[i]);
data.splice(ind, 1);
}
}
})
console.log(data);
I am receiving an array of strings from a server in the following format:
var fruitsStrings = ["apple", "banana", "orange" ];
Is it possible to convert this into an array of objects, like below?
var fruitsObjects = [
{
fruit: "apple"
},
{
fruit: "banana"
},
{
fruit: "orange"
}
];
All the object properties will be the same. Happy to use pure JavaScript or jQuery. I've tried using jquery.extend but as this adds unique IDs before each value it's not really fit for my purpose.
Thank you.
you can use .map
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = fruitsStrings.map(function( val, i ) {
return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = fruitsStrings.map(function( val, i ) {
return {fruit:val};
});
document.write(JSON.stringify(fruitsObjects));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
fruitsStrings.forEach(function (item) {
fruitsObjects.push({ fruit: item });
});
Working demo.
Try this:
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
$.map( fruitsStrings, function( val, i ) {
fruitsObjects.push({ fruits: val });
});
A simple Array.prototype.map will do:
var fruitsStrings = ["apple", "banana", "orange"],
fruitsArray = fruitsStrings.map(function (a) { return { fruit: a } });
document.write('<pre>' + JSON.stringify(fruitsArray, 0, 4) + '</pre>');
You could also use this function where you can specify the key.
function toObjects(key,arr) {
var objects = [];
for (var i = 0; i < arr.length; ++i){
var obj = {};
obj[key] = arr[i];
objects[i] = obj;
}
return objects;
}
var fruitsStrings = ["apple", "banana", "orange" ];
toObjects('fruit',fruitsStrings);
// [{fruit: "apple"},{fruit: "banana"},{fruit: "orange"}]
Try this:
var fruitsStrings = ["apple", "banana", "orange" ];
var fruitsObjects = [];
fruitsStrings.map(function(v,i){
fruitsObjects.push({'fruit':v});
});
console.log(fruitsObjects);
Working Demo
I want to create a function like this, but I want the variable name and colour to be properties of this function, which means I just have to give them value when construct the function and do not have to declare them each time I call the function.
function A(input) {
var name = ["USA", "Japan", "India"]; // make it properties
var color = ["blue", "red", "green"]; // make it properties
var index = name.indexOf(input);
return color[index];
}
To make it clear, let me show my ideal code like this:
function A(input) {
var index = this.name.indexOf(input);
return this.color[index];
}
A.name = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];
Is it possible to set the function some properties like object? Thanks
Finally the problem is solved by module pattern, please attach to the accepted answer.
A module pattern could do this, but it will make the properties private (I don't know if it's what you need):
var A = (function() {
var name = ["USA", "Japan", "India"];
var color = ["blue", "red", "green"];
return function(input) {
var index = name.indexOf(input);
return color[index];
};
})();
The easiest way you can do this via passing the values in the parameter.
function A(input, name, color) {
var index = name.indexOf(input);
return color[index];
}
//Can be called like this
A("USA", ["USA", "Japan", "India"], ["blue", "red", "green"]);
Alternatively you can pass an object to a then just get from it.
function A(objectInput) {
var input = objectInput.input ? objectInput.input : "",
name = objectInput.name objectInput.name : [],
color = objectInput.color ? objectInput.color : [],
index = name.indexOf(input);
return color[index];
}
//Called like this.
A({
input: "USA",
name: ["USA", "Japan", "India"],
color: ["blue", "red", "green"]
});
function A(input) {
var index = A.country.indexOf(input);
return A.color[index];
}
A.country = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];
console.log(A("USA")); //Blue
Don't use name as property name, it returns function name by default.
Better code style:
function A(input) {
return A.colors[input];
}
A.colors = {
"USA": "blue",
"Japan": "red",
"India": "green"
}
My aim is to get a json array like this one:
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];
How can I get the below code to build up an array like the above one?
this.dependentProperties = []; //array
function addDependentProperty(depName, depValue) {
dependentProperties.push(new Array(depName, depValue));
}
By using the push method I end up having a json notation like this one:
args:{[["test1",1],["test2",2]]}
dependentProperties.push({name: depName, value: depValue});
var args = [{ name: 'test', value: 1 }, { key: 'test2', value: 2}];
...this is an array where each element is a associated-array (=hash, =object).
dependentProperties.push(new Array(depName, depValue));
...you are pushing a (sub-)Array into the parent array. That's not the same as an associative array. You now have a heterogeneous array.
dependentProperties.push({name: depName, value: depValue});
...This is pushing an associated-array into your top-level array. This is what you want. Luca is correct.
newObject = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": true,
"interests": [ "Reading", "Mountain Biking", "Hacking" ]
}
var myarray = [];
var myJSON = "";
for (var i = 0; i < 10; i++) {
var item = {
"value": i,
"label": i
};
myarray.push(item);
}
myJSON = JSON.stringify({myarray: myarray});