Push object keys and its values to array - javascript

I have an object like this:
{
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}
I want to store each key with its value to an array in javascript or typescript like this
[["id":23], ["name":"Jacob"], ["link":{......, ......}]] and so on
I am doing this so that I can append an ID for each.
My best guess I would loop through the array and append an ID/a flag for each element, which I don't know how to do as well.... how to address this issue ? thanks

var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[prop] = obj[prop];
arr.push(innerObj)
}
}
console.log(arr);
here is demo https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview

p.forEach( function (country) {
country.forEach( function (entry) {
entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
});
});

you can try to use experimental Object.entries:
let obj = {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}};
console.log(Object.entries(obj).map(item => ({[item[0]]:item[1]})));
for unsupported browsers you can use polyfill: https://github.com/es-shims/Object.entries

You could use an iterative/recursive approach with the object and their nested parts. It works for any depths.
function getKeyValue(object) {
return Object.keys(object).reduce(function (result, key) {
return result.concat(
object[key] && typeof object[key] === 'object' ?
getKeyValue(object[key]) :
[[key, object[key]]]
);
}, []);
}
var data = { id: 23, name: "Jacob", link: { rel: "self", link: "www.abc.com" }, company: { data: { id: 1, ref: 324 } } };
console.log(getKeyValue(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }

You can use the Object.keys method to get an array of the keys, then use the Array#map method to return a new array containing individual objects for each property.
This ES6 one-liner should do it:
const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));
Or in ES5:
function splitObject(o) {
return Object.keys(o).map(function(e) {
return Object.defineProperty({}, e, {
value: o[e],
enumerable: true
});
});
}

var res = [];
_.transform( {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company": {
"data": {
"id": 1,
"ref": 324
}
}
}, function(result, value, key) {
res.push(key +':'+value);
}, {});
You can use underscore

Supported in all major browser, including IE11
Object.entries() gives you exactly this.
const obj = {
id: 23,
name: 'Jacob',
link: {
rel: 'self',
link: 'www.abc.com'
},
company: {
data: {
id: 1,
ref: 324
}
}
};
Object.entries(obj);
// output:
[
[
"id",
23
],
[
"name",
"Jacob"
],
[
"link",
{
"rel": "self",
"link": "www.abc.com"
}
],
[
"company",
{
"data": {
"id": 1,
"ref": 324
}
}
]
]

var obj=[{"Name":ABC,"Count":123},{"Name":XYZ,"Count":456}];
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[0] = obj[prop];
arr.push(innerObj[0]);
}
}
/* Here above exmple innerobj index set to 0 then we will get same data into arr if u not menstion then arr will conatins arr[0] our result.
then we need to call first record obj arr[0][0] like this*/

const foo = { "bar": "foobar", "foo": "foobar" }
Object.entries(foo)
should result in:
[["bar", "foobar"], ["foo", "foobar"]]
maybe there's a function to pass to convert all commas to colons
Here's the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Related

How can I get items in data array with recursive?

I have a data array
var data=[{
"key": "KUZEY",
"items": [
{
"key": "MARMARA",
"items": [
{
"key": "T100",
"items": [
{
"Ref": 1,
"ApprovedReserveQuantity": 1
}
]
}
]
},
{
"key": "MARMARA 2",
"items": [
{
"key": "T100",
"items": [
{
"Ref": 2,
"ApprovedReserveQuantity": 1
}
]
}
]
}
] }]
İ want to get items when i call function. how can do that recursiveMethod?
groupedItems=recursiveMethod(data)
groupedItems==>[{"Ref": 1,"ApprovedReserveQuantity": 1},{"Ref": 2,"ApprovedReserveQuantity": 1}]
groupedItems:any[]=[];
recursiveMethod(element){
if(element.items==null)
this.groupedItems.push(element)
if (element.items != null){
let i;
for(i=0; i < element.items.length; i++){
this.recursiveMethod(element.items[i]);
}
}
}
it's worked
Couldn't find any 'key' checking in your answer.
Even though I don't trust my function completely, and am confused for as why it worked, It can be reusable if you tweak/adjust it.
const extractInnermostByKey = (data, targetKey, res = []) => {
data.forEach((obj) => {
for (let key of Object.keys(obj)) {
if (key === targetKey) {
// console.log(res); observe res
res.shift();
res.push(...obj[key]);
return extractInnermostByKey(res, targetKey, res);
}
}
});
return res;
};
const groupedItems = extractInnermostByKey(data, 'items');
console.log(groupedItems);

Build array from another array if some key are identical using JavaScript

I have an array of data. Some of the key in the array are same. I would like to create a new array based on the key and add the other data.
This is my array
var myObjOne = [
{
"name":"John",
"id":1,
"car":"maruti"
},
{
"name":"John",
"id":2,
"car":"wolks"
},
{
"name":"John",
"id":3,
"car":"bmw"
},
{
"name":"Peter",
"id":4,
"car":"alto"
},
{
"name":"Peter",
"id":5,
"car":"swift"
}
];
I would like to convert the array in to the below format.
var myObj = [
{
"name":"John",
"items": [
{ "id":1, "car":"maruti" },
{ "id":2, "car":"wolks" },
{ "id":3, "car":"bmw" }
]},
{
"name":"Peter",
"items": [
{ "id":4, "car":"alto" },
{ "id":5, "car":"swift" },
]
}
];
I am working on a node environment.
You can create an object using Array#reduce first which maps name with items, and then create the final array by looping over the intermediate map using a for...of loop:
var source = [{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}];
const map = source.reduce((acc, {name, ...obj}) => {
if (!acc[name]) {
acc[name] = [];
}
acc[name].push(obj);
return acc;
}, {});
const result = [];
for (let[name, items] of Object.entries(map)) {
result.push({name, items});
}
console.log(result);
Array.reduce is at rescue.This method accepts an accumulator and current
item. Check in the accumulator if there exist an object where the value of name property is John or Peter
var myObjOne = [{
"name": "John",
"id": 1,
"car": "maruti"
},
{
"name": "John",
"id": 2,
"car": "wolks"
},
{
"name": "John",
"id": 3,
"car": "bmw"
},
{
"name": "Peter",
"id": 4,
"car": "alto"
},
{
"name": "Peter",
"id": 5,
"car": "swift"
}
];
var newObj = myObjOne.reduce(function(acc, curr, currIndex) {
// using findIndex to check if there exist an object
// where the value of the name property is John, Peter
// if it exist it will return the index else it will return -1
let ifNameExist = acc.findIndex(function(item) {
return item.name === curr.name;
})
// if -1 then create a object with name and item property and push
// it to the accumulator
if (ifNameExist === -1) {
let nameObj = {};
nameObj.name = curr.name;
nameObj.items = [];
nameObj.items.push({
id: curr.id,
car: curr.car
})
acc.push(nameObj)
} else {
// if such an object already exist then just update the item array
acc[ifNameExist].items.push({
id: curr.id,
car: curr.car
})
}
return acc;
}, []);
console.log(newObj)
Use .reduce to group by name, and use .find inside the reducer to find if the matching name has already been added:
const input=[{"name":"John","id":1,"car":"maruti"},{"name":"John","id":2,"car":"wolks"},{"name":"John","id":3,"car":"bmw"},{"name":"Peter","id":4,"cars":"alto"},{"name":"Peter","id":5,"cars":"swift"}]
const output = input.reduce((a, { name, ...item }) => {
const foundNameObj = a.find(nameObj => nameObj.name === name);
if (foundNameObj) foundNameObj.items.push(item);
else a.push({ name, items: [item] });
return a;
}, []);
console.log(output);

transform array of strings into custom structure

I need to convert this array of strings into a special structure
https://github.com/jonmiles/bootstrap-treeview
This is my Input String array:
******************
"productone"
"productone\level2\level3"
"productwo"
"productwo\level2\level3\level4"
"productwo\level2\level3.1\level4\level5"
"productwo\level2\level3.2\level4\level5"
so can you imagine this:
"memory"
"memory\ram"
"memory\ram\ddr\sodimm\533mhz\4gb"
"memory\ram\ddr\sodimm\533mhz\8gb"
"memory\ram\ddr\sodimm\533mhz\16gb"
"memory\ram\ddr\sodimm2\633mh\4gb
"memory\ram\ddr\sodimm2\633mh\16gb
"memory\disk"
and so on....
*******************
And I need this Output (pay attention at return correct order output):
var jsondata = [
{
"text": "productone",
"nodes":[ {"text": "level2",
"nodes":[{"text": "level3"}]
}]
},
{
"text": "productwo",
"nodes":[{"text": "level2"},
"nodes":[{"text": "level3",
"nodes":[{text:level4}]
}]
}]
}
}]
Any suggestion?
I threw away my previous answer to replace it with this one.
This should do exactly what you want.
var src = [
"productone",
"productone\\level2\\level3",
"productwo\\level2\\level3\\level4",
"productone\\level2\\dog",
"productone\\level2\\dog\\bark",
"productwo\\level2\\level3a\\level4a",
"productwo\\level2\\level3\\level4\\level5",
"productwo\\food\\desserts\\cookies",
"productwo\\food\\desserts\\cakes",
"productwo\\food\\desserts\\pies",
"productone\\level2\\cat",
"productone\\level2\\cat\\meow"
]
function tempToObj(temp) {
var result = [];
Object.keys(temp).forEach(
function(key) {
var obj = {
text: key
};
var nodes = tempToObj(temp[key]);
if (nodes.length > 0) {
obj.nodes = nodes;
}
result.push(obj);
}
);
return result;
}
function strsToObj(strList) {
var result = [];
var tempResult = {};
function buildNode(parts, idx, obj) {
var key = parts[idx];
obj[key] = obj[key] || {};
idx++;
if (idx < parts.length) {
buildNode(parts, idx, obj[key]);
}
}
strList.forEach(
function(str) {
var parts = str.split('\\');
buildNode(parts, 0, tempResult);
}
);
return tempToObj(tempResult);
}
var obj = strsToObj(src);
console.log(JSON.stringify(obj,0,2));
I found it much easier to just build of an object structure and then convert it into the format you wanted. That simplified the parsing algorithm and yet prevents rebuilding everything each time.
The result of the code above is this:
[
{
"text": "productone",
"nodes": [
{
"text": "level2",
"nodes": [
{
"text": "level3"
},
{
"text": "dog",
"nodes": [
{
"text": "bark"
}
]
},
{
"text": "cat",
"nodes": [
{
"text": "meow"
}
]
}
]
}
]
},
{
"text": "productwo",
"nodes": [
{
"text": "level2",
"nodes": [
{
"text": "level3",
"nodes": [
{
"text": "level4",
"nodes": [
{
"text": "level5"
}
]
}
]
},
{
"text": "level3a",
"nodes": [
{
"text": "level4a"
}
]
}
]
},
{
"text": "food",
"nodes": [
{
"text": "desserts",
"nodes": [
{
"text": "cookies"
},
{
"text": "cakes"
},
{
"text": "pies"
}
]
}
]
}
]
}
]
I have solve my problem and I have transform to Javacript pure code this
Brandon Clapp article
You can string#split each string inside array#map and use array#reduceRight to check for nodes and text value inside your result object. If text key is present at a level, reassign your object to nodes key and populate text key with the current text value.
var strings = ["productone","productone\\level2\\level3","productwo\\level2\\level3\\level4"];
const result = strings.map(string => string.split('\\').reduceRight((r,text, index) => {
if(r['text'])
r['nodes'] = [Object.assign({}, r)];
r['text'] = text;
return r;
},{}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could take a hash table with a nested approach by taking the given part strings as identifiert for nested objects for collecting all data.
Later this proposal deletes unwanted nodes without content.
This approach works for unsorted data.
var array = ["productone", "productone\\level2\\level3", "productwo\\level2\\level3\\level4"],
result = [],
hash = { _: result };
array.forEach(function (a) {
a.split('\\').reduce(function (r, k) {
if (!r[k]) {
r[k] = { _: [] };
r._.push({ text: k, nodes: r[k]._ });
}
return r[k];
}, hash);
});
result.forEach(function clean(o) {
if (o.nodes.length) {
o.nodes.forEach(clean);
} else {
delete o.nodes;
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

combine json array into one json array by id

I want to merge item and purchases array of json into one by matching their property value.
Here's the source :
{
"item": [
{
"invoiceId": 1
},
{
"invoiceId": 2
},
{
"invoiceId": 3
}
],
"purchase": [
{
"id": "1",
"date": "12/1/2014"
},
{
"id": "2",
"date": "12/1/2014"
},
{
"id": "3",
"date": "12/1/2014"
}
]
}
I want to produce something like this :
{
"combined": [
{
"invoiceId": 1,
"id": "1",
"date": "12/1/2014"
},
{
"invoiceId": 2,
"id": "2",
"date": "12/1/2014"
},
{
"invoiceId": 3,
"id": "3",
"date": "12/1/2014"
}
]
}
How can I match the item.invoiceId with purchase.id?
Solution
assuming obj is your object
var new_obj = {combined:[]};
obj["purchase"].forEach(function(a) {
obj["item"].forEach(function(b){
if (+b["invoiceId"]===(+a["id"])) {
a["invoiceId"] = b["invoiceId"] || 0;//WILL MAKE INVOICEID 0 IF IT IS NOT DEFINE. CHANGE 0 TO YOUR NEEDS
new_obj.combined.push(a);
}
});
});
How it works
The first .forEach() loops through obj.purchase. Then we loop through obj.item To check if their is a matching invoiceId (if you don't need to make sure their is a matching invoiceId, use the alternate code). Then, we simply add a new value to the new_obj
The result (copied from console) is:
{
"combined":[
{
"id":"1",
"date":"12/1/2014",
"invoiceId":1
},
{
"id":"2",
"date":"12/1/2014",
"invoiceId":2
},
{
"id":"3",
"date":"12/1/2014",
"invoiceId":3
}
]
}
Alternative Code
Use this if you don't need to make sure, invoiceId is there
var new_obj = {combined:[]};
obj["purchase"].forEach(function(a){a["invoiceId"]=a["id"];new_obj.combined.push(a);});
One way of achieving what you want will be
var result = {};
var getMatchingPurchase = function(invoiceId) {
return data.purchase.filter(function(purchase) {
return invoiceId == purchase.id;
})[0];
};
result.combined = data.item.map(function(invoice) {
var purchase = getMatchingPurchase(invoice.invoiceId);
return {
invoiceId: invoice.invoiceId,
id: purchase.id,
date: purchase.date
};
});
console.log(result);
It will print like bellow
{ combined:
[ { invoiceId: 1, id: '1', date: '12/1/2014' },
{ invoiceId: 2, id: '2', date: '12/1/2014' },
{ invoiceId: 3, id: '3', date: '12/1/2014' } ] }
Note:- I'm using map and filter functions which are not supported in IE8. If you want to use in IE8 you have to use for loop.
If you have to support old browsers like IE8 (poor guy...), note that the native forEach might not be supported, in this case you can use lodash for cross-browser compatibility:
function getCombinedResult(source){
var combinedList = [];
_.each(source.item, function(item){
_.each(source.purchase, function(purchase){
if (item['invoiceId'].toString() != purchase['id'].toString()) return;
var combinedItem = _.extend(item, purchase)
combinedList.push(combinedItem);
});
})
return {"combined": combinedList};
}

Concatenate two json object

is there any way to Aggregation two json object together and assign the result to the first object
i have tow Json object and i want to Aggregation them into one object
<script type="text/javascript">
$(document).ready(function () {
var FirstObject= [
{ "label": "salem", "actor": "" },
{ "label": "Aragorn", "actor": "Viggo Mortensen" },
{ "label": "Arwen", "actor": "Liv Tyler" },
{ "label": "Bilbo Baggins", "actor": "Ian Holm" },
{ "label": "Boromir", "actor": "Sean Bean" },
{ "label": "Frodo Baggins", "actor": "Elijah Wood" },
{ "label": "Gandalf", "actor": "Ian McKellen" },
{ "label": "Gimli", "actor": "John Rhys-Davies" },
{ "label": "Gollum", "actor": "Andy Serkis" },
{ "label": "Legolas", "actor": "Orlando Bloom" },
{ "label": "Meriadoc Merry Brandybuck", "actor": "Dominic Monaghan" },
{ "label": "Peregrin Pippin Took", "actor": "Billy Boyd" },
{ "label": "Samwise Gamgee", "actor": "Sean Astin" }
];
$("#search").keyup(function () {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "WebService1.asmx/GetDocumentNames",
data: '{ }',
success: function (data) {
**FirstObject =data.d**
},
error: function () { aler("Salem Error"); }
}
);
});
});
</script>
so on the statement FirstObject =data.d i want the Aggregation
Use jQuery extend like this:
// first argument tells jQuery's extend to deep copy the properties
$.extend( true, FirstObject, data.d );
quote from jQuery documentation:
Merge two objects recursively, modifying the first.
Your variable FirstObject is actually an array, and assuming what you receive is not an Array but a JSON Object to append or aggregate it to the array, you just need to call the Array's method push.
FirstObject.push(data.d);
If what you're receiving is a JSON Array rather that a JSON Object, you could use the concat method in the array.
FirstObject.concat(data.d);
Take a look in below example:
var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}];
var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}];
jsonArray1 = jsonArray1.concat(jsonArray2);
If you want to merge the JSON objects and maintain the common keys.
var object1 = {
'key1': 10,
'key2': 'Hello ',
'key3': [
'I',
'am'
],
'key4': {
'key5': 'Hi',
'key6': 11
}
};
var object2 = {
'key1': 11,
'key2': 'World',
'key3': [
'an',
'Array'
],
'key4': {
'key5': ' there',
'key6': '#SomeRandomString'
}
};
function isArray(value) {
return Object.prototype.toString.call(value) === '[object Array]';
}
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}
var result = {};
for (var key in object1) {
if (object1.hasOwnProperty(key) && object2.hasOwnProperty(key)) {
//check if the value is of type array (works for key 3)
if (isArray(object1[key]) && isArray(object2[key])) {
result[key] = [];
for (var i in object1[key]) {
result[key].push(object1[key][i])
}
for (var i in object2[key]) {
result[key].push(object2[key][i])
}
}
//check if the value is of type object (works for key 4)
else if (isObject(object1[key])) {
result[key] = {};
for (var key_inner in object1[key]) {
if (object1[key].hasOwnProperty(key_inner) && object2[key].hasOwnProperty(key_inner)) {
result[key][key_inner] = object1[key][key_inner] + object2[key][key_inner];
}
}
} else {
result[key] = object1[key] + object2[key];
}
}
}
//console.log(JSON.stringify(result));
console.log(result);
You can use Object.assign() method to concatenate a json object. The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.[1]
var o1 = { a: 1 }, o2 = { b: 2 }, o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

Categories