2

I have several objects like this:

{'id[0]': 2}
{'url[0]': 11}
{'id[1]': 3}
{'url[1]': 14}

And I want to get something like this:

[{id:2, url:11}, {id:3, url:14}]

Also I have lodash in my project. Maybe lodash have some method for this?

7
  • i think we need to parse the keys of objects using regex . Commented Dec 8, 2016 at 7:33
  • 2
    how you are carrying these several objects Commented Dec 8, 2016 at 7:33
  • 3
    @Viplock in hand . Commented Dec 8, 2016 at 7:33
  • Are you trying to merge every two objects? Commented Dec 8, 2016 at 7:34
  • 1
    @guest271314 no maybe he is trying to merge using this [0] and [1] Commented Dec 8, 2016 at 7:35

4 Answers 4

5

You could use a regular expression for the keys and create a new object if necessary. Then assign the value to the key.

var data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }],
    result = [];

data.forEach(function (a) {
    Object.keys(a).forEach(function (k) {
        var keys = k.match(/^([^\[]+)\[(\d+)\]$/);
        if (keys.length === 3) {
            result[keys[2]] = result[keys[2]] || {};
            result[keys[2]][keys[1]] = a[k];
        }
    });
});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2

This is an ES6 solution based on @NinaScholz solution.

I assume that the objects have only one property each, like the ones presented in the question.

  1. Combine the array of objects to one large object using Object#assign, and convert to entries with Object.entries.
  2. Iterate the array using Array#reduce.
  3. Extract the original key an value from each entry using array destructuring.
  4. Extract the wanted key and index using a regex and array destructuring.
  5. Then create/update the new object at the index using object spread.

const data = [{ 'id[0]': 2 }, { 'url[0]': 11 }, { 'id[1]': 3 }, { 'url[1]': 14 }];

// combine to one object, and convert to entries
const result = Object.entries(Object.assign({}, ...data)) 
  // extract the original key and value
  .reduce((r, [k, value]) => {
    
    // extract the key and index while ignoring the full match
    const [, key, index] = k.match(/^([^\[]+)\[(\d+)\]$/);

    // create/update the object at the index
    r[index] = {...(r[index] || {}), [key]: value }; 

    return r;
  }, []);

console.log(result);

Comments

0

var arr = [{'id[0]': 2},
{'url[0]': 11},
{'id[1]': 3},
{'url[1]': 14}];

var result = [];

arr.forEach(function(e, i, a){
  var index = +Object.keys(e)[0].split('[')[1].split(']')[0];//get the number inside []
  result[index] = result[index] || {}; //if item is undefined make it empty object 
  result[index][Object.keys(e)[0].split('[')[0]] = e[Object.keys(e)[0]];//add item to object
})

console.log(result);

Comments

0

You can use for loop, .filter(), RegExp constructor with parameter "\["+i+"\]" where i is current index, Object.keys(), .reduce(), .replace() with RegExp /\[\d+\]/

var obj = [{
  "id[0]": 2
}, {
  "url[0]": 11
}, {
  "id[1]": 3
}, {
  "url[1]": 14
}];

var res = [];
for (var i = 0; i < obj.length / 2; i++) {
  res[i] = obj.filter(function(o) {
             return new RegExp("\[" + i + "\]").test(Object.keys(o))
           })
           .reduce(function(obj, o) {
             var key = Object.keys(o).pop();
             obj[key.replace(/\[\d+\]/, "")] = o[key];
             return obj
           }, {})
}

console.log(res);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.