how to get the value in any way if key does match with "Item"
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
console.log(data[i].includes("Item"));
//Expecting phone and case
}
for-in allows you to loop through the keys in an object. Not to be confused with for-of, which loop through elements in an array.
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
for(let datum of data)
{
for(let key in datum)
{
if(key.includes("Item"))
{
console.log(datum[key]);
}
}
}
In the simple way just change data[i].includes("Item") to data[i].keys().includes("Item").
BUT! Could we have some alternative data set here? For example:
const data = [{
"Item-55566": "phone",
"SomeKey: "Some Value",
123123: "Numeric key with value"
},
{
"Items-44555": "Case",
"Another-key": "Another value"
}
];
In this case you need to put some changes in your code to find correct keys & values:
for(let i = 0; i<data.length; i++) {
data[i].keys().forEach(v=>{
String(v).includes("Item") && console.log("Got index: ${i}, key: ${v}, value: ${data[i][v]}")
})
}
The for loop iterates through the two objects, so you can check to see whether the object has that particular property using hasOwnProperty()
const data = [
{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
},
];
/* How to get value if index found by Item */
for (let i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("Item-55566")) {
console.log(data[i]);
}
}
If you want to keep your loop (good that it's only one loop compared to other answers) you can do it with Object.keys and values:
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
if(Object.keys(data[i])[0].includes('Item')){
console.log(Object.values(data[i])[0]);
}
}
You can use .filter to filter all items of the data array which includes Item text.
Then you can use .map to render new value from each object comes from data array.
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var filteredItems = data.filter(item => Object.keys(item)[0].includes("Item"));
console.log(filteredItems.map(item => Object.values(item)[0]));
Refactor code - By using .reduce()
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var res = data.reduce((prev, curr) =>
{
var entries = Object.entries(curr)[0];
if(entries[0].includes("Item"))
prev.push(entries[1]);
return prev;
}, []);
console.log(res);
Related
Here's my input object —
{
"email": [
"abc"
],
"name": [
"def",
"ghi"
],
"number": [
"123",
"456"
]
}
Here's what I'm hoping to get as output —
[
{
"email":"abc",
"name":"def",
"number":"123"
},
{
"email":"abc",
"name":"ghi",
"number":"123"
},
{
"email":"abc",
"name":"def",
"number":"456"
},
{
"email":"abc",
"name":"ghi",
"number":"456"
}
]
And, here's my code —
const input = {
"email": [
"abc"
],
"name": [
"def",
"ghi"
],
"number": [
"123",
"456"
]
};
const keys = Object.keys(input);
const values = Object.values(input);
let depth = [];
let output = [];
values.forEach(value => depth.push(value.length));
depth = depth.reduce((a, b)=> a*b, 1);
let dict = {};
for (let i = 0; i < depth; i++) {
for (let j = 0; j < keys.length; j++) {
let key = keys[j];
if (input[key][i] !== undefined) {
dict[key] = input[key][i];
}
}
console.log(dict);
output.push(dict);
}
console.log(output);
Your approach by calculating the product of the lengths is certainly one that can work. But there are some problems with the implementation that make it fail:
With let dict = {}; you only create one object, and that object is being pushed to the result array repeatedly. Any mutation to that object will thus be seen in very entry of that result array. So you should at least create that dict object in every iteration of the outer loop
i will in many cases exceed the length of the input[key] array, so input[key][i] will be undefined. Yet you need to pick a value from that array. You should use modular logic to translate such i to a valid index, and then use the remainder of that i in the next iteration of the inner loop -- to pick a value from the next array.
Here is a slight adaptation of your code to tackle those issues. I also moved it into a function:
function cartesian(input) {
let keys = Object.keys(input);
let depth = Object.values(input).reduce((product, {length}) => product * length, 1);
let result = [];
for (let i = 0; i < depth; i++) {
let j = i;
let dict = {};
for (let key of keys) {
let size = input[key].length;
dict[key] = input[key][j % size];
j = Math.floor(j / size);
}
result.push(dict);
}
return result;
}
const input = {
"email": [
"abc"
],
"name": [
"def",
"ghi"
],
"number": [
"123",
"456"
]
};
let result = cartesian(input);
console.log(result);
This answer is based on the answers provided on this question.
Step 1
Extract the three arrays:
const {email, name, number} = input;
Step 2
Perform the cartesian product:
const cartesian = (...a) => a.reduce((a, b) => a.flatMap(d => b.map(e => [d, e].flat())));
const product = cartesian(email, name, number);
Step 3
Recompose the output:
const output = product.map(triple => ({email: triple[0], name: triple[1], number: triple[2]}));
You can replace the cartesian function with other functions found in the related question, accordingly to the target version of ES you mean to support.
#pilchard proposes a more generic version, which doesn't need you to specify the properties, but just performs the cartesian product on all the ones available within an object, and it is:
const result = cartesian(...Object.entries(input).map(([k, vs]) => vs.map(v => [[k, v]]))).map(Object.fromEntries)
I have a object variable and i want to push into my object a new { key: "value" } but with a loop and using loop index.
Something like this:
let headers = {
product_title: "Product Name",
action: "Status",
quantity: "Quantity",
priority: "Priority",
};
for (let i = 0; i < bigger; i++) {
headers = { ...headers, ...{ 'org_{i}': i } };
}
is there a way to do something like this or add unique key with indexes?
Finally i need something like below:
let headers = {
...old data
key_1: "",
key_2: "",
key_3: "",
};
There's an ES6 thing called "computed properties" which allows regular JS enclosed in [] to form a string key...
let headers = {
product_title: "Product Name",
action: "Status",
quantity: "Quantity",
priority: "Priority",
};
for (let i = 0; i < 5; i++) {
headers = { ...headers, ['key_' + i]: i }
}
console.log(headers)
Neat, but this creates a throw-away object for each iteration. Skipping the literal with the spread, you can use older JS, more efficiently...
let headers = {
product_title: "Product Name",
action: "Status",
quantity: "Quantity",
priority: "Priority",
};
for (let i = 0; i < 5; i++) {
headers['key_' + i] = i
}
console.log(headers)
To add new key-value into object you can literally just use
headers[key] = value
But if you are intending to set keys dynamically I suggest you to check this out
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
Try something like below
const output = [...Array(bigger)].reduce((acc, curr, index) => {
return ({ ...headers, ...acc, [`org_${index}`]: index })
}, {});
I'm having an array of object,in which I'm storing the billkey and billvalue as attributes. I want billkey to be the key and billvalue to be the value of that particular key.
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
}
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
}];
And I want to convert it into this format:
var log=[
{
Name:"ABC",
Department:"Computer"
},
{
Name:"XYZ",
Department:"Electrical"
}];
How about this simple solution. Hope it helps!
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
},
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
}];
var arr = [];
var finalObj = [];
for(var i in log){
var someObject = log[i];
for(var j in someObject){
arr.push(someObject[j]);
}
}
for(var k = 0; k < arr.length; k+=4){
finalObj.push({
Name: arr[k+1],
Department: arr[k+3]
});
}
console.log(finalObj);
create the result using forloop
// store the values
var logs=[];
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
},
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
},
];
loop the first array
for (i = 0; i < log.length; i++) {
// create empty variable for storing the values
var index = new Array();
// insert the first index value to key
index[log[i].billkey] = log[i].billvalue
// insert the second index value to key
index[log[i+1].billkey] = log[i+1].billvalue
// insert the result in to new array
logs.push(index);
// increment the i with 1
i=i+1;
}
console.log(logs);
You could use Array#reduce and use the remainder operator as witch for using either the last object or create a new one.
var log = [{ billkey: "Name", billvalue: "ABC" }, { billkey: "Department", billvalue: "Computer" }, { billkey: "Name", billvalue: "XYZ" }, { billkey: "Department", billvalue: "Electrical" }],
result = log.reduce(function (r, a, i) {
var o = {};
if (i % 2) {
r[r.length - 1][a.billkey] = a.billvalue;
} else {
o[a.billkey] = a.billvalue;
r.push(o);
};
return r;
}, []);
console.log(result);
I have a constructor in JavaScript which contains 2 properties Key and Values array:
function Test(key, values) {
this.Key = key;
this.Values = values.map(values);
}
Then I created an array of Test objects:
var testObjectArray = [];
testObjectArray.push(new Test(1, ['a1','b1']), new Test(2, ['a1','b2']));
Now I want to map the testObjectArray to single key-value pair array which will be similar to :
[
{ "Key" : "1", "Value" : "a1" },
{ "Key" : "1", "Value" : "b1" },
{ "Key" : "2", "Value" : "a2" },
{ "Key" : "2", "Value" : "b2" },
]
How can I achieve this using array's map function?
I guess you are misunderstanding map(). Here is a very simple example:
a = [1, 2, 3]
b = a.map(function (i) { return i + 1 })
// => [2, 3, 4]
Here is the MDN documentation for map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map. So you should rethink the usage of map in your case. By the way - your example is not working, because values is not a function.
Here is a possible solution:
res = [];
a = [['a1','b1'],['a1','b2']];
for (var i = 0; i < a.length; ++i) {
for(var j = 0; j < a[i].length; ++j) {
res.push({"Key": i + 1 , "Value" : a[i][j]});
}
}
I'm sure there are other ways, but here's something with plain Javascript that does what you want:
http://jsfiddle.net/KXBRw/
function Test(key, values) {
this.Key = key;
this.Values = values;//values.map(values);
}
function getCombinedTests(testObjectArray) {
var all = [];
for (var i = 0; i < testObjectArray.length; i++) {
var cur = testObjectArray[i];
for (var j = 0; j < cur.Values.length; j++) {
all.push({"Key": ""+cur.Key, "Value": cur.Values[j]});
}
}
return all;
}
var testObjectArray1 = [];
testObjectArray1.push(new Test(1, ['a1','b1']), new Test(2, ['a1','b2']));
var combined = getCombinedTests(testObjectArray1);
console.log(combined);
You could use .reduce(), .concat() and .map() for this.
var result = testObjectArray.reduce(function(res, obj) {
return res.concat(obj.Values.map(function(val) {
return {"Key":obj.Key, "Value":val};
}));
}, []);
Not sure what values.map(values); was supposed to do though.
DEMO: http://jsfiddle.net/BWNGr/
[
{
"Key": 1,
"Value": "a1"
},
{
"Key": 1,
"Value": "b1"
},
{
"Key": 2,
"Value": "a1"
},
{
"Key": 2,
"Value": "b2"
}
]
If you're super strict about not creating unnecessary Arrays, you can tweak it a little and use .push() instead of .concat().
var result = testObjectArray.reduce(function(res, obj) {
res.push.apply(res, obj.Values.map(function(val) {
return {"Key":obj.Key, "Value":val};
}));
return res;
}, []);
DEMO: http://jsfiddle.net/BWNGr/1/
You can achieve this by using the following for each loop where each key value pair will be pushed to an array.
var mapped = [];
$.each(testObjectArray, function(key, value) {
for(x in value.Values) {
mapped.push({
Key: value.Key,
Value: x
});
}
});
My Json array looks like this:
var data =
{
"categories":
{
"category1":
{
"Name": "Maps",
"Id": 3,
"orderInList": 1
},
"category2":
{
"Name": "Books",
"Id": 2,
"orderInList": 2
}
}
};
When I write do console.log(data), the 'key' to the object is formatted like:
| key | value |
categories[category1][Id] "3"
How can I iterate over this in a for loop (without using JQuery's $.each) so I can tell which key, value pairs are Names, Id's or orderInList's?
Working Jsfiddle
Something like this should work:
for (var category in data['categories']) {
for (var key in data['categories'][category]) {
var value = data['categories'][category][key];
// Now do whatever you want based on key...
switch (key) {
case 'Name':
// Whatever
break;
default:
break;
}
}
}
In any case, key and value in the inner loop will hold the key and value of your nested object, and category will hold the category.
The potentially confusing thing about this is that object properties can be accessed like array values in Javascript.
So consider the code below:
var some_object = {
a: 0
};
// These two lines do the same thing, even though some_object is not an array.
some_object.a = 1;
some_object['a'] = 1;
Your outer categories object is an object that contains many child objects. You can iterate through these children objects using a for...in loop.
for (var category in data.categories) {
// here you can access `category.Name`, `.Id`, and `.orderInList`
}
Checkout this
var data = {
"categories": {
"category1": {
"Name": "Maps",
"Id": 3,
"orderInList": 1
},
"category2": {
"Name": "Books",
"Id": 2,
"orderInList": 2
}
}
};
function represent(obj) {
var reprs = [];
for (var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
if (obj[key] instanceof Object) {
var result = represent(obj[key]);
for (var i = 0; i < result.length; i++) {
reprs.push("[" + key + "]" + result[i]);
}
}
else {
reprs.push("[" + key + "] = " + obj[key]);
}
}
return reprs;
}
console.log(represent(data));
//output
["[categories][category1][Name] = Maps",
"[categories][category1][Id] = 3",
"[categories][category1][orderInList] = 1",
"[categories][category2][Name] = Books",
"[categories][category2][Id] = 2",
"[categories][category2][orderInList] = 2"]
which key, value pairs are Names, Id's or orderInList's?
I think you can add code at the recursion terminate condition to check if the key is equal to Names Id or orderInList