how to make an array from an object? - javascript

i have this object, each key contains an index after the underscore at the end of it, so i can do something and try to gather each one with the same index together and get the expected obj, i don't know how to do it with underscore of even plain java-script
var obj = {
phoneNumber_0 : "2",
phoneNumber_1 : "0",
phoneType_0 : "Home",
phoneType_1 : "Work"
}
var expected = [
{number: '2', type: 'home'},
{number: '0', type: 'work'},
]

You could split the keys of the object for the name and for index. Then build a new object if necessary and assign the value of the actual property.
var object = { phoneNumber_0: "2", phoneNumber_1: "0", phoneType_0: "Home", phoneType_1: "Work" },
result = [];
Object.keys(object).forEach(function (k) {
var p = k.split('_');
result[p[1]] = result[p[1]] || {};
result[p[1]][p[0]] = object[k];
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

I guess this will do what you have been looking for,
var obj = {
phoneNumber_0 : "2",
phoneNumber_1 : "0",
phoneType_0 : "Home",
phoneType_1 : "Work"
}
var finalArray = []
Object.keys(obj).map((key,index) => {
if (obj['phoneNumber_' + index] || obj['phoneType_' + index])
finalArray.push({ number: obj['phoneNumber_' + index], type:obj['phoneType_' + index]})
})
console.log(finalArray)

It would be your expected result
var obj = {
phoneNumber_0 : "2",
phoneNumber_1 : "0",
phoneType_0 : "Home",
phoneType_1 : "Work"
}
var expected = []
for(var key in obj){
if(key.indexOf('phoneNumber_') === 0){
var kn = key.replace('phoneNumber_', '')
expected.push({number: obj[key], type: (obj['phoneType_' + kn]||'').toLowerCase()})
}
}
console.log(expected)

Related

JavaScript get unique array object data by 2 object unique

I have problem with find uniqueness by 2 value. I want do something like SQL GROUP BY Tag_No and PlatformID. I want find unique value by Tag_No and PlayformID where both value can't be duplicate
I have tried something like below, but it only works for one unique 'Tag_No'
var NewTag = [
{Tag_No:'xxx01',PlatformID:'12',Details:'example1'},
{Tag_No:'xxx02',PlatformID:'13',Details:'example2'},
{Tag_No:'xxx03',PlatformID:'14',Details:'example3'},
{Tag_No:'xxx05',PlatformID:'5',Details:'example4'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example5'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example6'},
]
var tmp = [];
var result = [];
if (NewTag !== [] /* any additional error checking */ ) {
for (var i = 0; i < NewTag.length; i++) {
var val = NewTag[i];
if (tmp[val.Tag_No] === undefined ) {
tmp[val.Tag_No] = true;
result.push(val);
}
}
}
console.log('result',result)
expected value is
result=[{Tag_No:'xxx01',PlatformID:'12',Details:'example1'},
{Tag_No:'xxx02',PlatformID:'13',Details:'example2'},
{Tag_No:'xxx03',PlatformID:'14',Details:'example3'},
{Tag_No:'xxx05',PlatformID:'5',Details:'example4'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example5'},
]
use array.filter instead.
This filters your array on duplicates no matter what structure you have.
Reference
var NewTag = [
{Tag_No:'xxx01',PlatformID:'12',Details:'example'},
{Tag_No:'xxx02',PlatformID:'13',Details:'example'},
{Tag_No:'xxx03',PlatformID:'14',Details:'example'},
{Tag_No:'xxx05',PlatformID:'5',Details:'example'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example'},
]
const uniqueArray = NewTag.filter((value, index) => {
const _value = JSON.stringify(value);
return index === NewTag.findIndex(obj => {
return JSON.stringify(obj) === _value;
});
});
console.log('result',uniqueArray)
You can use hash grouping approach:
const data = [{Tag_No:'xxx01',PlatformID:'12',Details:'example'},{Tag_No:'xxx02',PlatformID:'13',Details:'example'},{Tag_No:'xxx03',PlatformID:'14',Details:'example'},{Tag_No:'xxx05',PlatformID:'5',Details:'example'},{Tag_No:'xxx05',PlatformID:'12',Details:'example'},{Tag_No:'xxx05',PlatformID:'12',Details:'example'}];
const result = Object.values(data.reduce((acc, item) => {
const hash = [item.Tag_No, item.PlatformID].join('---');
acc[hash] ??= item;
return acc;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }
Here is my solution:
let NewTag = [
{Tag_No:'xxx01',PlatformID:'12',Details:'example'},
{Tag_No:'xxx02',PlatformID:'13',Details:'example'},
{Tag_No:'xxx03',PlatformID:'14',Details:'example'},
{Tag_No:'xxx05',PlatformID:'5',Details:'example'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example'},
{Tag_No:'xxx05',PlatformID:'12',Details:'example'},
]
let temp=[]
let result=[];
NewTag.forEach(tag=>{
let key=tag.Tag_No+"\t"+tag.PlatformID;
if (!temp.includes(key)){
temp.push(key);
result.push(tag)
}
});
console.log(result)
You could use Set to check for uniqueness
const NewTag = [
{ Tag_No: "xxx01", PlatformID: "12", Details: "example" },
{ Tag_No: "xxx02", PlatformID: "13", Details: "example" },
{ Tag_No: "xxx03", PlatformID: "14", Details: "example" },
{ Tag_No: "xxx05", PlatformID: "5", Details: "example" },
{ Tag_No: "xxx05", PlatformID: "12", Details: "example" },
{ Tag_No: "xxx05", PlatformID: "12", Details: "example" },
]
const uniquePairSet = new Set()
const res = NewTag.reduce((acc, el) => {
const Tag_No_PlatformID = `${el.Tag_No}-${el.PlatformID}`
if (!uniquePairSet.has(Tag_No_PlatformID)) {
uniquePairSet.add(Tag_No_PlatformID)
acc.push(el)
}
return acc
}, [])
console.log("result", res)
References
Set

Javascript : Add Key & Value at specific index in array of Object

I have array of Object like this.
let arr = [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}]
let newVal = arr.map(function(el) {
if(el.age > 25){
var o = Object.assign({}, el);
o.gender = 'male';
return o;
}
})
console.log("New Val : " , newVal)
I would like to add {gender:'male'} to object where age is > 25
It says undefined to other objects.
Any help would be great.
Thank You.
You need to return the value if the object doesn't match the condition. Since you haven't retrned anything from from inside map if the condition is not fulfilled, you get undefined for the other objects
let arr = [{
name: "abc",
age: 26
}, {
name: "xyz",
age: 23
}, {
name: "pqr",
age: 10
}]
let newVal = arr.map(function(el) {
if (el.age > 25) {
var o = Object.assign({}, el);
o.gender = 'male';
return o;
}
return el; // return value here
})
console.log("New Val : ", newVal)
issue with your code is already solved in other answer by Shubham, ie when if clause is not executed you are not returning anything.
but i think forEach might be cleaner here
if you want to keep the original array you can copy it using copyArr = [...arr]
let arr = [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}]
arr.forEach(function(el) {
if(el.age > 25)
el.gender = 'male';
})
console.log("New Val : " , arr)
It's missing the return statement when the condition is false.
You can do this in one line using an arrow function as follow:
let arr = [{name:"abc",age:26},{name:"xyz",age:23},{name:"pqr",age:10}],
newVal = arr.map((el) => Object.assign({}, el, el.age > 25 ? {gender: "male"} : {}));
console.log("New Val:", newVal);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You get a new array with map. Inside, you need to take either an copy of the object with a new property or the original object.
let array = [{ name: "abc", age: 26 }, { name: "xyz", age: 23 }, { name: "pqr", age: 10 }],
result = array.map(object => object.age > 25
? { ... object, gender: 'male' }
: object
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to add array values to an object

I have an array with few values. I want to iterate over array and add those values to an object as value starting from second object element which has null value. I cannot figure out how can I do it properly. Here is my code
let objectParameters = {
"current_lang" : currentLang,
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
arrayValues .forEach(function(item) {
//Add array value to an object
}
Desired output
let objectParameters = {
"current_lang" : currentLang,
"project_name" : "Project name",
"project_type" : "Project Type",
"min_price" : 150,
"max_price" : 950
}
Came up with this :
let objectParameters = {
"current_lang" : "currentLang",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
};
let arrayValues = ["Project name", "Project Type", 150, 950],
keys = Object.keys(objectParameters);
keys.shift() // Removing the first key, which is not null
keys.forEach( (key,i) => objectParameters[key] = arrayValues[i])
console.log(objectParameters)
You can get all the properties of an object with
Object.keys(objectParameters)
as an array and assign them values from your arrayValues
Like that:
let objectParameters = {
"current_lang" : "en",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
let params = Object.keys(objectParameters);
for(let i = 1; i < params.length; i++) {
objectParameters[params[i]] = arrayValues[i-1];
}
console.log(objectParameters);
Using for in loop to iterate through the object and shift() to get the first array element each iteration, in all cases we rely on the order, that is probably not a good approach.
let objectParameters = {
"current_lang" : "currentLang",
"project_name" : null,
"project_type" : null,
"min_price" : null,
"max_price" : null
}
let arrayValues = ["Project name", "Project Type", 150, 950];
for(let p in objectParameters){
if(!objectParameters[p])
objectParameters[p] = arrayValues.shift()
}
console.log(objectParameters)
I don't see necessary to use hasOwnProperty in this case.
If you know the index of the corresponding value in the array you dont need the loop and can just do:
objectParameters["project_name"] = arrayValues[0]
objectParameters["project_type"] = arrayValues[1]
...
if you have the array values when youre creating the object you can just use them at the object creation time:
let objectParameters = {
"current_lang" : "en",
"project_name" : arrayValues[0],
...
}
Well, if you got ordered array and object, here this code might help you:
var obj = {
'first': '1',
'second': '2'
};
var arr = ['first', 'sec'];
Object.keys(obj).forEach(function (key, arrIndex) {
obj[key] = arr[arrIndex];
});
Then you edit and optimize it the way you want.
Little improvement, thank to #Jeremy Thille
If your arrayValues format value will be same then you could use separate keys and use reduce() method for your arrays values and Destructuring_assignment.
DEMO
const keys = ["project_name", "project_type", "min_price", "max_price"],
arrayValues = ["Project name", "Project Type", 150, 950];
let result = arrayValues.reduce((r, v, i) => {
return { ...r,
[keys[i]]: v
}
}, {current_lang:navigator.language});
console.log(result)
.as-console-wrapper {max-height: 100% !important;top: 0;}

Comparing 2 array values push only first result

I have an array which i need to compare it's values - and if there are duplication - i want to store them in array, for example :
obj1 = [{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"manager_id":2,"name":"kenny"},
{"manager_id":4,"name":"stan"}]
obj2 = [{"employees_id":1,"name":"dan"},
{"employees_id":1,"name":"ben"},{"employees_id":1,"name":"sarah"},
{"employees_id":2,"name":"kelly"}]
If "manger_id" === "employees_id - then the result would be :
// {1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"},
{"employees_id":1,"name":"sarah"}]};
I've tried :
var obj1 = [{
"manager_id": 1,
"name": "john"
}, {
"manager_id": 1,
"name": "kile"
}, {
"manager_id": 2,
"name": "kenny"
}, {
"manager_id": 4,
"name": "stan"
}];
var obj2 = [{
"employees_id": 1,
"name": "dan"
}, {
"employees_id": 1,
"name": "ben"
}, {
"employees_id": 1,
"name": "sarah"
}, {
"employees_id": 2,
"name": "kelly"
}];
var res = obj1.concat(obj2).reduce(function(r, o) {
r[o.manager_id] = r[o.employees_id] || [];
r[o.manager_id].push(o);
return r;
}, {});
console.log(res);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
As you can the results of the "manager_id" aren't added - only one - when there should be more
if manager_id === employees_id // should output in the first key
{1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"},
{"employees_id":1,"name":"sarah"}]};
As you can see there are several common id's
r[o.manager_id] = r[o.employees_id] || []; in this statement if a manager didn't have an employee_id the array was being reset for that id.
One way doing it right is this:
var res = obj1.concat(obj2).reduce(function(r, o) {
var id;
if(o.hasOwnProperty('manager_id')) {
id = o['manager_id'];
}
else {
id = o['employees_id'];
}
r[id] = r[id] || [];
r[id].push(o);
return r;
}, {});
The problem relies on this line:
r[o.manager_id] = r[o.employees_id] || [];
You should have in mind that some objects in your arrays have the manager_id and some other don't, they have the employees_id instead, so you have to evaluate that first with this line:
var itemId = o.manager_id || o.employees_id;
Try this code:
var res = obj1.concat(obj2).reduce(function(r, o) {
var itemId = o.manager_id || o.employees_id;
r[itemId] = r[itemId] || [];
r[itemId].push(o);
return r;
}, {});

How to map a javascript array to another javascript array

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
});
}
});

Categories